Skip to content

Instantly share code, notes, and snippets.

@tot-ra
Created March 18, 2013 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tot-ra/5192182 to your computer and use it in GitHub Desktop.
Save tot-ra/5192182 to your computer and use it in GitHub Desktop.
Text DIFF with highlighting
function htmlDiff($old, $new, $exceptions = array()) {
$ret = '';
$diff = diff(explode(' ', $old), explode(' ', $new), $exceptions);
foreach ($diff as $k) {
if (is_array($k)) {
$ret .= (!empty($k['d']) ? "<del style='background:#FFFF00;'>" . implode(' ', $k['d']) . "</del> " : '') . (!empty($k['i']) ? "<ins style='background:#00FF00;'>" . implode(' ', $k['i']) . "</ins> " : '');
}
else {
$ret .= $k . ' ';
}
}
return $ret;
}
function diff($old, $new, $exceptions = 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]) && in_array($ovalue, $exceptions) ? $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)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment