如何在php中找到包含另一个字符串子串的字符串作为子字符串?

时间:2015-06-17 16:41:02

标签: php regex string substring

$a = "The quick brown fox jumps over a lazy dog.";
$b = array("The lazy dog sleeps under the tree.", "...", ...);

如何在字符串$b[0]中找到包含“懒狗”的$a?问题是,我事先并不知道搜索到的子字符串是“懒狗”,类似于数组的array_intersect

1 个答案:

答案 0 :(得分:0)

来自github的

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