比较具有差异和相似性的字符串

时间:2016-07-11 13:23:26

标签: php

我用这个函数比较字符串..

但是如何在返回数组中再添加一个属性,两个字符串中有所有相似之处?

    width seq
[1]   201 CCATCCCAGGGGTGATGCCAAGTGATTCCA...CTAACTCTGGGGTAATGTCCTGCAGCCGG

1 个答案:

答案 0 :(得分:1)

从我得到的你想要一个修改只显示相似之处:

<?php
function get_decorated_diff($old, $new, $get_similarity=false){
    $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";
    if($get_similarity)
    $get_similarity = "<ins style='background-color:#ccffcc'>$start $end</ins>"; 
    return array("old"=>$old, "new"=>$new, "similarity"=>$get_similarity);
}

$string_old = "The quick brown fox jumped over the lazy dog";
$string_new = "The quick white rabbit jumped over the lazy dog";
$diff = get_decorated_diff($string_old, $string_new, true);
echo "<table border=1>
    <tr align=center>
        <td>old</td>
        <td>new</td>
        <td>similarity</td>
    </tr>
    <tr>
        <td>".$diff['old']."</td>
        <td>".$diff['new']."</td>
        <td>".$diff['similarity']."</td>
    </tr>
</table>";

?>

输出:

enter image description here

相关问题