$a = "The quick brown fox jumps over a lazy dog.";
$b = array("The lazy dog sleeps under the tree.", "...", ...);
如何在字符串$b[0]
中找到包含“懒狗”的$a?
问题是,我事先并不知道搜索到的子字符串是“懒狗”,类似于数组的array_intersect
答案 0 :(得分:0)
This Gist可能需要一些调整,但应该得到你想要的东西:
function longest_common_substring($words) {
$words = array_map('strtolower', array_map('trim', $words));
$sort_by_strlen = create_function('$a, $b', 'if (strlen($a) == strlen($b)) { return strcmp($a, $b); } return (strlen($a) < strlen($b)) ? -1 : 1;');
usort($words, $sort_by_strlen);
$longest_common_substring = array();
$shortest_string = str_split(array_shift($words));
while (sizeof($shortest_string)) {
array_unshift($longest_common_substring, '');
foreach ($shortest_string as $ci => $char) {
foreach ($words as $wi => $word) {
if (!strstr($word, $longest_common_substring[0] . $char)) {
break 2;
}
}
$longest_common_substring[0] .= $char;
}
array_shift($shortest_string);
}
usort($longest_common_substring, $sort_by_strlen);
return trim(array_pop($longest_common_substring));
}
// usage:
echo longest_common_substring(array('The quick brown fox jumped over the lazy dog', 'I jumped over the lazy bear'));