Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Return the common parts from 2 strings.
*
* @param string $str1
* @param string $str2
* @param bool $from_end
* return string
*/
function str_common(string $str1, string $str2, $from_end = false) : string
{
if ($from_end) {
$str1 = strrev($str1);
$str2 = strrev($str2);
}
for ($i=0; $i < strlen($str1); $i++) {
if ($str1[$i] !== $str2[$i]) {
break;
}
}
$return = substr($str1, 0, $i);
return $from_end ? strrev($return) : $return;
}
// Example usage:
$ver1 = 'The quick brown fox jumped over the lazy dog.';
$ver2 = 'The quick brown fox leapt over the lazy dog.';
echo str_common($ver1, $ver2);
// -> 'The quick brown fox '
echo str_common($ver1, $ver2, true);
// -> ' jumped over the lazy dog.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.