Skip to content

Instantly share code, notes, and snippets.

@simonhamp
Created November 7, 2017 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simonhamp/c43fa60f69de0bb99e08ccf50a1fbaf6 to your computer and use it in GitHub Desktop.
Save simonhamp/c43fa60f69de0bb99e08ccf50a1fbaf6 to your computer and use it in GitHub Desktop.
<?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