我使用strcasecmp()
来比较两个字符串,如果字符串中有不同的字符串,我该如何打印出来。
例如:
$string1 = "Hello World;";
$string2 = "Hellow World";
if(strcasecmp($string1, $string2) ==0){
echo $string1;
echo $string2;
}else{
echo #the difference;
}
应打印出来:
";" "Hellow"
答案 0 :(得分:1)
您可以尝试这样的事情:
<?php
$string1 = "Hello World;";
$string2 = "Hellow World";
/* Transform each string into character array */
$s1 = str_split($string1);
$s2 = str_split($string2);
/* Let's print them just so you can see */
print_r($s1);
print_r($s2);
/* Check if the character from first string, exists in string 2 */
foreach ($s1 as $key1 => $value1) {
if (($key2 = array_search($value1, $s2)) ) { //If the character from the first string, is found in the second string...
if (strcasecmp($value1, $s2[$key2]) == 0) { //Make sure the case matches
unset($s1[$key1]); //Remove the matched character from the first string.
unset($s2[$key2]); //Remove the matched character from the second string.
}
}
}
/* Note that because 0 also means false, we need to check
* if the characters at 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 the two strings. They are: \n";
print_r($differences);
}
上面的代码检查字符串1中的每个字符是否都存在于字符串2中。如果字符确实存在,我们将它从两个数组中删除,以便在每个数组中找不到任何未找到的字符。