比较 php 中的两个字符串,获取不匹配的字符数


Compare two strings in php get number of characters that don't match?

有些用户喜欢用大写写写帖子标题,这很烦人。与其要求他们再写一遍,我想知道他们写的标题中有多少百分比是大写的,这样如果他们超过 50%,我就应用 strtolower。

我的想法是将它们的字符串转换为小写,看看它与原始字符串有何不同(3 个不同的字符意味着最初有 3 个大写字符):

$title = 'AAAA';
$title2 =  strtolower($title);

如何将$title与 $title 2 进行比较以获得不匹配的字符数?

例如:

$title = 'AAAa'
$title2 = 'aaaa'
$differences = '3';
$title = 'AAAa';
$title2 =  strtolower($title);
$differences = 0;
for ($i=0,$l=strlen($title); $i < $l; $i++) {
  if ($title{$i} !== $title2{$i}) {
    $differences++;
  }
}
你可以

试试levenshtein($title,$title2,1,1000,1000000)。在结果数字中,单位告诉您必须添加多少个字母,千个单位告诉您更改了多少个字母(可能是您在这里最想要的),数百万个单位告诉您已删除的字母数量。

使用PHP的本机函数similar_text(),我认为你会得到你想要的。使用示例:

$title = 'AAAa';
$title2 = 'aaaa';
similar_text ( $title , $title2, $percentege );
echo $percentege . '%'; // Output: 25%

您也可以这样使用它:

echo similar_text ( $title , $title2 ); // Output: 1

第一种用法返回两个字符串之间的相似性百分比,第二种用法返回两个字符串具有的相似字符的数量。

希望对您有所帮助!