DiffMatchPatch\DiffToolkit::commontOverlap PHP Method

commontOverlap() public method

Determine if the suffix of one string is the prefix of another.
public commontOverlap ( string $text1, string $text2 ) : integer
$text1 string First string.
$text2 string Second string.
return integer The number of characters common to the end of the first string and the start of the second string.
    public function commontOverlap($text1, $text2)
    {
        // Cache the text lengths to prevent multiple calls.
        $text1_length = mb_strlen($text1);
        $text2_length = mb_strlen($text2);
        // Eliminate the null case.
        if (!$text1_length || !$text2_length) {
            return 0;
        }
        // Truncate the longer string.
        if ($text1_length > $text2_length) {
            $text1 = mb_substr($text1, -$text2_length);
        } elseif ($text1_length < $text2_length) {
            $text2 = mb_substr($text2, 0, $text1_length);
        }
        $text_length = min($text1_length, $text2_length);
        // Quick check for the worst case.
        if ($text1 == $text2) {
            return $text_length;
        }
        // Start by looking for a single character match
        // and increase length until no match is found.
        // Performance analysis: http://neil.fraser.name/news/2010/11/04/
        $best = 0;
        $length = 1;
        while (true) {
            $pattern = mb_substr($text1, -$length);
            $found = mb_strpos($text2, $pattern);
            if ($found === false) {
                break;
            }
            $length += $found;
            if ($found == 0 || mb_substr($text1, -$length) == mb_substr($text2, 0, $length)) {
                $best = $length;
                $length += 1;
            }
        }
        return $best;
    }