在数组中查找相似的字符串


find similar occurance of string in an array

假设我们有一个数组

$t = array('red - blah blah', 'yellow @ blah blah', 'blue > blah blah');

我们如何在数组中找到相似的出现?在这种情况下,它会是"blah blah"。谢谢!

为了简单的解决方案,您可以尝试遍历第一个字符串的可能子字符串(从最长的字符串开始),然后在其他字符串中搜索它;如果找到,这就是你的结果。但是这种方法会消耗大量的处理器。

$firstString = $t[0];
for ($len = strlen($firstString); $len > 0; $len--) {
    for ($start = 0; $start + $len <= strlen($firstString); $start++) {
        $possibleCommonSubstring = substr($firstString, $start, $len);
        for ($idx = 1; $idx < count($t); $idx++) {
            if (!strpos($t[$idx], $possibleCommonSubstring)) {
                continue 2;
            }
        }
        return $possibleCommonSubstring;
    }
}

更多的一般性讨论和更有效的解决方案,可以在这里找到:http://en.wikipedia.org/wiki/Longest_common_substring_problem