Guest User

PHP diff

a guest
Mar 13th, 2013
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. function diff($old, $new){
  2.     $matrix = array();
  3.     $maxlen = 0;
  4.     foreach($old as $oindex => $ovalue){
  5.         $nkeys = array_keys($new, $ovalue);
  6.         foreach($nkeys as $nindex){
  7.             $matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1]) ?
  8.                 $matrix[$oindex - 1][$nindex - 1] + 1 : 1;
  9.             if($matrix[$oindex][$nindex] > $maxlen){
  10.                 $maxlen = $matrix[$oindex][$nindex];
  11.                 $omax = $oindex + 1 - $maxlen;
  12.                 $nmax = $nindex + 1 - $maxlen;
  13.             }
  14.         }  
  15.     }
  16.     if($maxlen == 0) return array(array('d'=>$old, 'i'=>$new));
  17.     return array_merge(
  18.         diff(array_slice($old, 0, $omax), array_slice($new, 0, $nmax)),
  19.         array_slice($new, $nmax, $maxlen),
  20.         diff(array_slice($old, $omax + $maxlen), array_slice($new, $nmax + $maxlen)));
  21. }
  22.  
  23. function htmlDiff($old, $new){
  24.  
  25.     // put space in front and behind tags, or they are seen as a word when replacing the one behind it or in front
  26.     $old = str_replace(array("<",">"), array(" <", "> "), $old);
  27.     $new = str_replace(array("<",">"), array(" <", "> "), $new);
  28.    
  29.     $ret = '';
  30.     $diff = diff(explode(' ', $old), explode(' ', $new));
  31.     foreach($diff as $k){
  32.         if(is_array($k))
  33.             $ret .= (!empty($k['d'])?"<del>".implode(' ',$k['d'])."</del> ":'').
  34.                 (!empty($k['i'])?"<ins>".implode(' ',$k['i'])."</ins> ":'');
  35.         else $ret .= $k . ' ';
  36.     }
  37.     return $ret;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment