Created
November 7, 2017 21:32
-
-
Save simonhamp/c43fa60f69de0bb99e08ccf50a1fbaf6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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