gpt4 book ai didi

PHP:找到多个字符串之间最大的重叠

转载 作者:行者123 更新时间:2023-12-03 02:20:59 24 4
gpt4 key购买 nike

我有这个数组:

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

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

最佳答案

更新

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

$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;
});

I need to extract the value "c123" like it is the biggest match for all strings in array

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

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);

关于PHP:找到多个字符串之间最大的重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com