Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Highlight string differences using `<del>` and `<ins>`
<?php
/**
* Generate two arrays:
* Values array: a list of elements as they appear in the diff
* Mask array: 0: unchanged, -1: removed, 1: added
*
* @param string $from
* @param string $to
* @return array
*/
function computeDiff($from, $to)
{
$diffValues = [];
$diffMask = [];
$dm = [];
$n1 = count($from);
$n2 = count($to);
for ($j = -1; $j < $n2; $j++) {
$dm[-1][$j] = 0;
}
for ($i = -1; $i < $n1; $i++) {
$dm[$i][-1] = 0;
}
for ($i = 0; $i < $n1; $i++) {
for ($j = 0; $j < $n2; $j++) {
if ($from[$i] === $to[$j]) {
$ad = $dm[$i - 1][$j - 1];
$dm[$i][$j] = $ad + 1;
} else {
$a1 = $dm[$i - 1][$j];
$a2 = $dm[$i][$j - 1];
$dm[$i][$j] = max($a1, $a2);
}
}
}
$i = $n1 - 1;
$j = $n2 - 1;
while (($i > -1) || ($j > -1)) {
if ($j > -1) {
if ($dm[$i][$j - 1] === $dm[$i][$j]) {
$diffValues[] = $to[$j];
$diffMask[] = 1;
$j--;
continue;
}
}
if ($i > -1) {
if ($dm[$i - 1][$j] === $dm[$i][$j]) {
$diffValues[] = $from[$i];
$diffMask[] = -1;
$i--;
continue;
}
}
{
$diffValues[] = $from[$i];
$diffMask[] = 0;
$i--;
$j--;
}
}
$diffValues = array_reverse($diffValues);
$diffMask = array_reverse($diffMask);
return [
'values' => $diffValues,
'mask' => $diffMask,
];
}
/**
* Highlight the string differences
*
* @param string $line1
* @param string $line2
* @return string
*/
function diff($line1, $line2)
{
$diff = computeDiff(str_split($line1), str_split($line2));
$diffval = $diff['values'];
$diffmask = $diff['mask'];
$n = count($diffval);
$pmc = 0;
$result = '';
for ($i = 0; $i < $n; $i++) {
$mc = $diffmask[$i];
if ($mc != $pmc) {
switch ($pmc) {
case -1:
$result .= '</del>';
break;
case 1:
$result .= '</ins>';
break;
}
switch ($mc) {
case -1:
$result .= '<del>';
break;
case 1:
$result .= '<ins>';
break;
}
}
$result .= $diffval[$i];
$pmc = $mc;
}
switch ($pmc) {
case -1:
$result .= '</del>';
break;
case 1:
$result .= '</ins>';
break;
}
return $result;
}
@u01jmg3
Copy link
Author

u01jmg3 commented Jan 30, 2020

Confu<del>zi</del><ins>s</ins>ed

Confuzised

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment