0

I have two strings which starts out the same, but at some point are different. I want to find how many characters the two strings share in common.

It seems like strpos is the opposite of this; it assumes that one string is found completely in another, but not necessarily at the starting offset.

I see a lot of questions which ask about finding common substrings when they aren't at the start, or when there are more than two strings, and this seems to complicate things quite a bit. I have just two strings, and they have a common prefix. IS there a PHP function to get the index at which these two strings differ?

Michael
  • 9,060
  • 14
  • 61
  • 123

2 Answers2

0

You can try using for loop by comparing character by character. Something like this

$str1 = 'MyStringFirst';
$str2 = 'MyStringSecond';
$match_from_left = '';
$count = 0;
$limit = strlen($str1) > strlen($str2) ? strlen($str2) : strlen($str1);
for($i = 0; $i < $limit; $i++){
    if($str1[$i] != $str2[$i]){
        break;
    } 
    $count++;
    $match_from_left .= $str1[$i];
}

echo 'Count: ' . $count . '<br />';
echo 'Match: ' . $match_from_left . '<br />';
MH2K9
  • 11,951
  • 7
  • 32
  • 49
-1

Similar question answered here: Find first character that is different between two strings

You can use the inbuilt PHP function similar_text(), however as pointed out below, this does not get the index, only a count of the number of same characters.

Community
  • 1
  • 1
Jacob Mulquin
  • 3,458
  • 1
  • 19
  • 22