PHP – DIFF source code

functions

It seems very simple. but very strong to use.
Actually, I used to use it onto my project frequently.

Thanks to_ https://github.com/paulgb/simplediff

 

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function diff($old, $new){
 
  $matrix = array();
  $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 htmlDiff($old, $new, $mode=0){
  $ret = ”;
  $diff = diff(preg_split(“/[s]+/”, $old), preg_split(“/[s]+/”, $new));
   
  foreach($diff as $k){
 
    if(is_array($k))
      if($mode == 0){ //추가/삭제 모두 표시
        $ret .= (!empty($k[‘d’])?”<span class=’deleted’>”.implode(‘ ‘,$k[‘d’]).”</span> “:”).
        (!empty($k[‘i’])?”<span class=’inserted’>”.implode(‘ ‘,$k[‘i’]).”</span> “:”);
      }else if($mode == 1){ //삭제 내용만 표시
        $ret .= (!empty($k[‘d’])?”<span class=’deleted’>”.implode(‘ ‘,$k[‘d’]).”</span> “:”);
      }else if($mode == 2){ //추가 내용만 표시
        $ret .= (!empty($k[‘i’])?”<span class=’inserted’>”.implode(‘ ‘,$k[‘i’]).”</span> “:”);
      }else $ret .= $k . ‘ ‘;
    else $ret .= $k . ‘ ‘;
 
  }
 
  return $ret;
}

댓글 남기기