简体   繁体   English

如何比较两个字符串并确定它们之间的差异?

[英]How can I compare two strings and determine their differences?

I have two strings like this: 我有两个这样的字符串:

$str1 = "this is
         a text";

$str2 = "this is a text
         which is edited";

As you see there is two difference between them, removed that <br> which is after is (in the $str1 ) and appending whic is edited . 正如你看到他们之间有两个差,卸下的<br>是后is (在$str1和附加whic is edited Now I need to detect those difference, How can I do that? 现在我需要发现这些差异,我该怎么做?

Actually I need to show to my website's users what's edited. 实际上我需要向我的网站用户展示编辑过的内容。 Something exactly like stackoverflow edit page (which highlights the difference with red and green colors). 完全类似于stackoverflow编辑页面(突出显示红色绿色的区别)。

If you load the php extension xdiff, then the command xdiff_string_diff will make an unified diff containing the differences between two strings for you. 如果你加载php扩展xdiff,那么命令xdiff_string_diff将为你创建一个包含两个字符串之间差异的统一差异。

<?
$str1 = "this is
         a text";
$str2 = "this is a text
         which is edited";

$diff = xdiff_string_diff($str1, $str2, 1);
if (is_string($diff)) {
    echo "Differences between two strings:\n";
    echo $diff;
}else{
    echo "The two strings look the same to me.";
}
?>
$Diff = str_replace($srt1, "", $str2);

应该管用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM