html diff

How to Diff Two Strings and Show the Difference in HTML

This php class will take two strings and return a html diff of them with the <ins> and <del> html tags representing what was deleted and inserted. It makes it easy to visually compare strings.

class Diff {

	public static function diffArray($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(
			self::diffArray(array_slice($old, 0, $omax), array_slice($new, 0, $nmax)),
			array_slice($new, $nmax, $maxlen),
			self::diffArray(array_slice($old, $omax + $maxlen), array_slice($new, $nmax + $maxlen)));
	}

	public static function htmlDiff($old, $new){
		$ret = '';
		$diff = self::diffArray(explode(' ', $old), explode(' ', $new));
		foreach($diff as $k){
			if(is_array($k)){
				$ret .= (!empty($k['d'])?'<del>'.implode(' ',$k['d']).'</del> ':'').(!empty($k['i'])?'<ins>'.implode(' ',$k['i']).'</ins> ':'');
			}else{
				$ret .= $k . ' ';
			}
		}
		return $ret;
	}

}

Example usage

echo Diff::htmlDiff('I went to the store', 'We went to the store');

Output

I We went to the store

Leave a Reply

Your email address will not be published. Required fields are marked *