您所说的问题也被称为the longest common substring problem。我发现an implementation for finding the longest common substring在字符串数组中。由于在原岗位,用法提到:
<?php
$array = array(
'PTT757LP4',
'PTT757A',
'PCT757B',
'PCT757LP4EV'
);
echo longest_common_substring($array);
// => T757
?>
相关的代码:
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)) {
// No match
break 2;
} // if
} // foreach
$longest_common_substring[0].= $char;
} // foreach
array_shift($shortest_string);
}
// If we made it here then we've run through everything
usort($longest_common_substring, $sort_by_strlen);
return array_pop($longest_common_substring);
}
很棒!由于OP想要按(最后一个)空格拆分,因此只需很小的添加:$ string = longest_common_substring($ array); echo substr($ string,0,strrpos($ string,'')); – sinisake
谢谢。我也使用谷歌,但不知道问题的名称,因为我的母语不是英语。 谢谢你的解决方案。 – Dany