Skip to content

Instantly share code, notes, and snippets.

@DmmitryIs
Last active February 13, 2017 13:33
Show Gist options
  • Save DmmitryIs/2d8d977d26324905714ad0f868245a13 to your computer and use it in GitHub Desktop.
Save DmmitryIs/2d8d977d26324905714ad0f868245a13 to your computer and use it in GitHub Desktop.
Find longest common parts of two strings
<?php
function commonParts($a, $b) {
$a = trim($a);
$b = trim($b);
$str = strlen($a) <= strlen($b) ? strtolower($a) : strtolower($b);
$pos = 0;
$max = 0;
while (strlen($str)) {
if (!empty(substr($str, $pos, 1)) && strpos($b, substr($str, $pos, 1)) !== FALSE) {
$part = substr($str, $pos);
$common = substr($str, $pos, 1);
while (strlen($part)) {
if (strpos($b, $common . substr($part, 0, 1)) !== FALSE && strpos($a, $common . substr($part, 0, 1)) !== FALSE) {
$common = $common . substr($part, 0, 1);
$pos++;
}
$part = substr($part, 1);
}
$result[] = $common;
$max = strlen($common) > $max ? strlen($common) : $max;
}
$str = substr($str, 1);
}
$result = array_filter($result, function($val) use($max) {
return strlen($val) == $max;
});
// Returns string if found only one common part and array if two or more
return count($result) == 1 ? array_shift($result) : $result;
}
print_r(commonParts('Doors', 'Kangaroo'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment