计算php中两个字符串之间的差异数?
我想比较两个字符串由于长度较短的字符串,并返回不同主题的数量。例如:计算php中两个字符串之间的差异数?,php,string,compare,Php,String,Compare,我想比较两个字符串由于长度较短的字符串,并返回不同主题的数量。例如: $first_str = "abcdez"; $second_str= "abhdx"; 现在由于$second\u str的长度较短,因此必须返回2。因为它们只在第三和第五个指数上有所不同。事实上,它们的指数是相等的。 在php中有它的函数吗?如果没有,你能帮我写代码吗?也许这有帮助。我从阿南特那里转达了他的意见 $first_str = "abcdez"; $second_str=
$first_str = "abcdez";
$second_str= "abhdx";
现在由于$second\u str
的长度较短,因此必须返回2。因为它们只在第三和第五个指数上有所不同。事实上,它们的指数是相等的。
在php中有它的函数吗?如果没有,你能帮我写代码吗?也许这有帮助。我从阿南特那里转达了他的意见
$first_str = "abcdez";
$second_str= "abhdx";
$first_str_array = str_split($first_str);
$second_str_array = str_split($second_str);
$first_count = count($first_str_array);
$second_count = count($second_str_array);
if (($first_count - $second_count) > 0) {
$count = $first_count - $second_count;
unset($first_str_array[$first_count-$count]);
} else if (($second_count - $first_count) > 0){
$count = $second_count - $first_count;
unset($second_str_array[$second_count-$count]);
}
$final_difference = array_diff($first_str_array,$second_str_array);
数组对于这样的东西很好。我没有测试它,但它应该可以工作
$a_first_str = str_split($first_str);
$a_second_str = str_split($second_str);
$diff=array_diff_assoc($a_second_str, $a_first_str);
将有一个数组显示要比较字符的差异?为什么
2
<代码>c、e
和z
不在第二个字符串中。@Patrick Mlr。对第一个字符串的第一个字符与第二个字符串的第一个字符…@Digipng这是您想要的:-可能是@Anant的倒数。但是我希望差异是5,因为两个字符串之间有5个差异。我猜OP没有回应我的评论。是的,我会的。现在只需count()
这个$diff
就可以得到差异的数量。我在末尾添加了count($final_difference),效果很好。感谢您提供最完整的答案:)