Count how many characters matched at the beginning when compare two string

I want to count how many characters matched the beginning when compare two string.

Here is one solution:

<?php 
echo '<br>$str1: ', $str1 = 'Hello World';
echo '<br>$str2: ', $str2 = 'Hello WoXld';

for($i2=1; $i2 <= strlen($str1); $i2++):
  $char = substr($str1, 0, $i2);
  $ok   = strcmp(substr($str1, 0, $i2), substr($str2, 0, $i2) );
  if($ok):
    echo '<h3>' .$ok .' &nbsp; ' .$char .'</h3>';
  else:
    echo '<h6>' .$ok .' &nbsp; ' .$char .'</h6>';
  endif;  
endfor;
echo '<br><br><br>';
?>    

Output:

Thanks for your help, it working fine and solved my problem…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.