I recently found a need to find the longest common substring in an array of strings in PHP. A couple of Google searches didn’t return any relevant solutions, so I decided to roll my own. I haven’t benchmarked this yet for large strings and/or arrays, but it does what I needed it to for my own purpose.
[gist id=1021218 file=longest_common_substring.php]
Example:
[gist id=1021218 file=longest_common_substring_example.php]
A little bit simpler solution, only for two strings.
It returns string.
function longestCommonSubstring( $str1, $str2, $case_sensitive=false)
{
$ret = array();
$len1 = mb_strlen($str1);
$len2 = mb_strlen($str2);
if (! $len1 || ! $len2)
return false;
// Find shorter
if ($len2 < $len1)
{
$t = $len1;
$len1 = $len2;
$len2 = $t;
$t = $str1;
$str1 = $str2;
$str2 = $t;
}
if (! $case_sensitive)
{
$str1 = mb_strtolower($str1);
$str2 = mb_strtolower($str2);
}
// Through chars.
for ($i = 0; $i<$len1; $i++)
{
// Next char is same?
$c1 = mb_substr($str1, $i, 1);
if ($c1 === mb_substr($str2, $i, 1))
{
$ret[] = $c1;
}
else
{
break;
}
}
return implode('', $ret);
}