2012-06-22 30 views

回答

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"; 
    } 
} 

也許如果你能詳細告訴我們你想要比較的方式,或者給我們一些例子,我們可以更容易地決定答案。

+0

我想higligh每個位是從其他 –

+0

@RanaMuhammadUsman不同也許會給我們帶來更多的細節 –

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()只知道不同的第一個字符,它會很有用。

0

稍加修改爲@阿爾文的腳本:

我有50KB Lorem存有串測試它在我的本地服務器,我取代所有「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; 
?>