我有一个代码来显示两个句子之间的差异。但我需要检查没有区分大小写。
<?php
function get_decorated_diff($old, $new){
$from_start = strspn($old ^ $new, "\0");
$from_end = strspn(strrev($old) ^ strrev($new), "\0");
$old_end = strlen($old) - $from_end;
$new_end = strlen($new) - $from_end;
$start = substr($new, 0, $from_start);
$end = substr($new, $new_end);
$new_diff = substr($new, $from_start, $new_end - $from_start);
$old_diff = substr($old, $from_start, $old_end - $from_start);
$new = "$start<ins style='background-color:#ccffcc'>$new_diff</ins>$end";
$old = "$start<del style='background-color:#ffcccc'>$old_diff</del>$end";
return array("old"=>$old, "new"=>$new);
}
$string_old = "Hello World!";
$string_new = "hello world!";
$diff = get_decorated_diff($string_old, $string_new);
echo "<table>
<tr>
<td>".$diff['old']."</td>
<td>".$diff['new']."</td>
</tr>
</table>";
?>
它显示Hello
和hello
的差异。但我需要在没有区分大小写的情况下显示差异
答案 0 :(得分:1)
尝试在一个案例中创建所有字符串,例如
function get_decorated_diff($old, $new){
$originalOld = $old;
$originalNew = $new;
$old = strtolower($old); //Add this line
$new = strtolower($new); //Add this line
$from_start = strspn($old ^ $new, "\0");
$from_end = strspn(strrev($old) ^ strrev($new), "\0");
$old_end = strlen($old) - $from_end;
$new_end = strlen($new) - $from_end;
$start = substr($new, 0, $from_start);
$end = substr($new, $new_end);
$new_diff = substr($originalNew, $from_start, $new_end - $from_start);
$old_diff = substr($originalOld, $from_start, $old_end - $from_start);
$new = "$start<ins style='background-color:#ccffcc'>$new_diff</ins>$end";
$old = "$start<del style='background-color:#ffcccc'>$old_diff</del>$end";
return array("old"=>$old, "new"=>$new);
}
答案 1 :(得分:1)
你可以在函数开头设置为小写
function get_decorated_diff($old, $new){
$old = strlower($old);
$new = strlower($new);
$from_start = strspn($old ^ $new, "\0");
.......
如果您需要保留原始值,您可以制作副本以便稍后返回原始内容
答案 2 :(得分:0)
将其设为小写并进行比较
$old_lower = strlower($old);
$new_lower = strlower($new);
$from_start = strspn($old_lower ^ $new_lower, "\0");
要使用不区分大小写的方式比较字符串,请使用strcasecmp
:
<?php
$string_old = "Hello World!";
$string_new = "hello world!";
if (strcasecmp($string_old, $string_new) == 0) {
echo '$string_old is equal to $string_new in a case-insensitive string comparison';
}
else {
echo = 'there is difference between $string_old with $string_new';
}
?>
答案 3 :(得分:0)
由于('a'^'A')=''即空格字符,无论如何都可以使用此代码进行比较:
$from_start = strspn($old ^ $new, "\0 ");
$from_end = strspn(strrev($old) ^ strrev($new), "\0 ");
但是,当要比较的字符不是字母时,它也会有错误匹配。