I've put together this extremely simple text diff function a while ago:
function diff($old, $new) {
$old = trim($old);
$new = trim($new);
if($old == $new) {
return $new;
}
$old = explode(" ", $old);
$new = explode(" ", $new);
$result = "";
$length = max(count($old), count($new));
for($i = 0; $i < $length; $i++) {
if(!isset($new[$i])) {
$result .= "<del>{$old[$i]}</del>";
continue;
}
if(!isset($old[$i])) {
$result .= "<ins>{$new[$i]}</ins> ";
continue;
}
if($old[$i] != $new[$i]) {
$result .= "<del>{$old[$i]}</del><ins>{$new[$i]}</ins> ";
continue;
}
$result .= "{$new[$i]} ";
}
$result = str_replace(array("</ins> <ins>", "</del> <del>"), " ", $result);
return trim($result);
}
$string1 = "Hello World!! Please review my diff function. Be gentle.";
$string2 = "Hello world! Please critique my diff function. Be extra vigilant.";
echo diff($string1, $string2);
// Hello <del>World!!</del><ins>world!</ins> Please <del>review</del><ins>critique</ins> my diff function. Be <del>gentle.</del><ins>extra vigilant.</ins>
The html output is:
Hello
World!!world! Pleasereviewcritique my diff function. Begentle.extra vigilant.
The purpose of the function wasn't something important, as I can't even remember why I built it (found in my sandbox directory, which is full of little experiments). Is it any good? I've always used PEAR Text_Diff for text diffs, but if I'm not doing anything inherently wrong in my simple function, I'd love to use it instead.
Any suggestions on an easy way to move html out of the function?