Forum Moderators: coopster

Message Too Old, No Replies

Compare 2 strings and return the common element

Is something like this built in to PHP?

         

penders

12:43 pm on Sep 2, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



So I want to return the common string between two strings, starting from the beginning - is there already a PHP function that will do something like this? It kinda feels as if there should be but I can't find it (before I go write one).

ie.

$str1 = "HelloWorld" 
$str2 = "HelloBob"

Comparing $str1 and $str2 would return:

"Hello"

penders

2:52 pm on Sep 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Well, I couldn't find a PHP function to do the job, so I wrote one...
function strCommon($str1,$str2) { 
$common = false;
$maxlen = min(strlen($str1),strlen($str2));
for ($i=0; $i<$maxlen; $i++) {
if ($str1[$i] == $str2[$i]) {
$common .= $str1[$i];
} else {
break;
}
}
return $common;
}

Returns (bool)false if no match.