comparison - PHP-print the difference in two strings -
i using strcasecmp()
compare 2 strings, how print out if there different in string.
for example:
$string1 = "hello world;"; $string2 = "hellow world"; if(strcasecmp($string1, $string2) ==0){ echo $string1; echo $string2; }else{ echo #the difference; }
should print out:
";" "hellow"
you can try this:
<?php $string1 = "hello world;"; $string2 = "hellow world"; /* transform each string character array */ $s1 = str_split($string1); $s2 = str_split($string2); /* let's print them can see */ print_r($s1); print_r($s2); /* check if character first string, exists in string 2 */ foreach ($s1 $key1 => $value1) { if (($key2 = array_search($value1, $s2)) ) { //if character first string, found in second string... if (strcasecmp($value1, $s2[$key2]) == 0) { //make sure case matches unset($s1[$key1]); //remove matched character first string. unset($s2[$key2]); //remove matched character second string. } } } /* note because 0 means false, need check * if characters @ index 0 match or not */ if (strcasecmp($s1[0], $s2[0]) == 0) { unset($s1[0]); unset($s2[0]); } $differences = array_merge($s1, $s2); if ($num_differences = sizeof($differences)) { echo "found $num_differences differences in 2 strings. are: \n"; print_r($differences); }
the code above checks see if each character in string 1 exists in string 2. if character exist, remove both arrays, characters not found leftover in each array.
Comments
Post a Comment