Shabat Closer

Tuesday, February 5, 2013

PHP - get difference words between 2 strings

et different words between 2 strings

function _diff($old, $new){$maxlen=0;
foreach($old as $oindex => $ovalue){$nkeys = array_keys($new, $ovalue);
foreach($nkeys as $nindex){$matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1]) ?
$matrix[$oindex - 1][$nindex - 1] + 1 : 1;
if($matrix[$oindex][$nindex] > $maxlen){
$maxlen = $matrix[$oindex][$nindex];
$omax = $oindex + 1 - $maxlen;
$nmax = $nindex + 1 - $maxlen;
}}}if($maxlen == 0)
return array(array('d'=>$old, 'i'=>$new));
return array_merge(_diff(array_slice($old, 0, $omax), array_slice
($new, 0, $nmax)),array_slice($new, $nmax, $maxlen),_diff(array_slice($old, $omax + $maxlen), array_slice
($new, $nmax + $maxlen)));}function getDiff($old, $new){$ret="";
$old=str_replace(array("\t","\r","\n",chr(10),chr(13)), " ",$old);
$old=str_replace(" ", " ",$old);
$new=str_replace(array("\t","\r","\n",chr(10),chr(13)), " ",$new);
$new=str_replace(" ", " ",$new);
$diff = _diff(explode(' ', $old), explode(' ', $new));
foreach($diff as $k){if(is_array($k)){$ret .=(empty($k['i']) ? '': implode(' ',$k['i']))." ";
}}return $ret;}



usage:

$text1="My first text abc";
$text2="My 2nd text def";
getDiff($text1,$text2); //return "2nd def"

No comments:

Post a Comment