【问题标题】:Count the number of differences between two string in php?计算php中两个字符串之间的差异数?
【发布时间】:2016-09-16 11:47:07
【问题描述】:

由于较短字符串的长度,我想比较两个字符串并返回差异主题的数量。例如:

$first_str = "abcdez";
$second_str= "abhdx";

现在由于$second_str 的长度较短,所以必须返回 2。因为它们仅在第三个和第五个索引上有所不同。实际上都是比较相等的索引。 php中是否有它的功能?如果没有,你能帮我写代码吗?

【问题讨论】:

  • 你想比较字符吗?
  • 为什么是2?第二个字符串中不存在cez
  • @Patrick Mlr。是的。第一个字符串的第一个字符与第二个字符串的第一个字符 ...
  • @Digipng 这就是你想要的:- eval.in/643475
  • 可能与@Anant、eval.in/643477相反。我希望差异为 5,因为 2 个字符串之间有 5 个差异。猜猜OP没有回应我的cmets..

标签: php string compare


【解决方案1】:

也许这会有所帮助。我从 Anant 那里分叉了评论。

$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);

【讨论】:

  • 我将 count($final_difference) 添加到 end 并且运行良好。谢谢你最完整的答案:)
【解决方案2】:

数组很适合这样的事情。我没有测试它,但它应该可以工作

$a_first_str = str_split($first_str);
$a_second_str = str_split($second_str);

$diff=array_diff_assoc($a_second_str, $a_first_str);

您将有一个显示差异的数组

【讨论】:

  • 是的,这就行了。现在只需 count()$diff,您就会知道差异的数量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 2011-05-16
相关资源
最近更新 更多