如何比较两个非常大的字符串

时间:2012-06-22 06:37:23

标签: php string compare

如何使用php比较两个大小为50Kb的大字符串。我想强调差分位。

3 个答案:

答案 0 :(得分:4)

使用XOR也可以找到两个字符串之间的差异:

$s = 'the sky is falling';
$t = 'the pie is failing';
$d = $s ^ $t;

echo $s, "\n";
for ($i = 0, $n = strlen($d); $i != $n; ++$i) {
        echo $d[$i] === "\0" ? ' ' : '#';
}
echo "\n$t\n";

输出:

the sky is falling
    ###      #
the pie is failing

XOR操作将产生一个字符串'\0',其中两个字符串相同,如果它们不同则不是'\0'。它不会比仅逐个字符地比较两个字符串更快,但如果你想通过使用strspn()只知道第一个不同的字符,它会很有用。

答案 1 :(得分:3)

您想输出diff吗?

也许这就是你想要的https://github.com/paulgb/simplediff/blob/5bfe1d2a8f967c7901ace50f04ac2d9308ed3169/simplediff.php

增加:

或者如果你想突出显示不同的每个字符,你可以使用这样的PHP脚本:

for($i=0;$i<strlen($string1);$i++){
    if($string1[$i]!=$string2[$i]){
        echo "Char $i is different ({$string1[$i]}!={$string2[$i]}<br />\n";
    }
}

也许如果你能详细告诉我们你想要比较的内容,或者给我们一些例子,我们就可以更容易地确定答案。

答案 2 :(得分:0)

@ Alvin剧本的一点修改:

我在我的本地服务器上使用50kb lorem ipsum字符串测试它,我将所有“a”替换为“4”并突出显示它们。它运行得非常快

    <?php
$string1 = "This is a sample text to test a script to highlight the differences between 2 strings, so the second string will be slightly different";
$string2 = "This is 2 s4mple text to test a scr1pt to highlight the differences between 2 strings, so the first string will be slightly different";
    for($i=0;$i<strlen($string1);$i++){                 
        if($string1[$i]!=$string2[$i]){
            $string3[$i] = "<mark>{$string1[$i]}</mark>";
            $string4[$i] = "<mark>{$string2[$i]}</mark>";
        }
        else {
            $string3[$i] = "{$string1[$i]}";
            $string4[$i] = "{$string2[$i]}";    
        }
    }
    $string3 = implode("",$string3);
    $string4 = implode("",$string4);

    echo "$string3". "<br />". $string4;
?>