3

我有这个数组:

$array = array('abc123', 'ac123', 'tbc123', '1ac123');

我想将每个字符串相互比较并找到最长的公共子字符串。在上面的示例中,结果将是c123

4

5 回答 5

9

更新

我完全误解了这个问题;目的是找到字符串数组之间最大的重叠:

$array = array('abc123', 'ac123', 'tbc123', '1ac123');

function overlap($a, $b)
{
        if (!strlen($b)) {
                return '';
        }

        if (strpos($a, $b) !== false) {
                return $b;
        }

        $left = overlap($a, substr($b, 1));
        $right = overlap($a, substr($b, 0, -1));

        return strlen($left) > strlen($right) ? $left : $right;
}

$biggest = null;
foreach ($array as $item) {
        if ($biggest === null) {
                $biggest = $item;
        }
        if (($biggest = overlap($biggest, $item)) === '') {
                break;
        }
}

echo "Biggest match = $biggest\n";

我不擅长递归,但我相信这应该可行;-)

旧答案

我可能会使用preg_grep()它;它返回一个数组,其中包含根据您的搜索字符串找到的匹配项:

$matches = preg_grep('/' . preg_quote($find, '/') . '/', $array);

或者,您可以使用array_filter()

$matches = array_filter($array, function($item) use ($find) {
    return strpos($item, $find) !== false;
});

我需要提取值“c123”,就像它是数组中所有字符串的最大匹配一样

我认为您在这里想要做的是根据字符串长度(即首先是最小字符串长度)对上述输出进行排序,然后取第一项:

if ($matches) {
    usort($matches,  function($a, $b) {
        return strlen($a) - strlen($b);
    });
    echo current($matches); // take first one: ac123
}

让我知道我是否错了。


如果您刚刚知道是否$find完全匹配某个元素:

$matching_keys = array_keys($array, $find, true); // could be empty array

或者:

$matching_key = array_search($find, $array, true); // could be false

或事件:

$have_value = in_array($find, $array, true);
于 2013-03-15T09:53:32.927 回答
0
in_array($find, $array);

如果它在数组中,则返回 true,但它必须是完全匹配的,在你的情况下它不会找到“ac123”。

如果你想看看它是否包含字符串,那么你需要遍历数组并使用 preg_match() 或类似的

于 2013-03-15T09:52:43.150 回答
0

您可以将 array_filter 与回调一起使用。

$output = array_filter ($input, function ($elem) { return false !== strpos ($elem, 'c123'); });
于 2013-03-15T09:58:33.560 回答
0
<?php
$array1 = array('abc123', 'ac123', 'tbc123', '1ac123');

if (in_array("c123", $array1)) {
    echo "Got c123";
}

?>
于 2013-03-15T10:00:10.370 回答
0

您可以使用此处使用的 in_array http://codepad.org/nOdaajNe 或使用此处使用的 array_search http://codepad.org/DAC1bVCi

看看能不能帮到你。。

文档链接: http: //php.net/manual/en/function.array-search.phphttp://www.php.net/manual/en/function.in-array.php

于 2013-03-15T10:17:55.873 回答