Once I needed a decent text diffing solution for SafePatch and after some searching couldn’t find one. So I’ve decided to write my own. It might not be very accurate but it’s very easy to use and has two modes – finding changes by line or inline (within one line). It also comes with built-in HTML generation although you need to style it yourself with CSS.
It has no dependencies and works out of the box in PHP 5.2 and up – simply include it and you’re ready to go.
Download QuickDiff here. Released in public domain. You can also check/fork/report issues to GitHub.
Inline | Diffes two flat strings treating line breaks as regular characters. Returns an array; each member is an array which 1st element specifies the type of difference found (- for removed piece, + for added, = for equal and change when a string portion was altered) and 2nd element holds what was deleted/added/equal. For change also a 3rd element is present indicating the new value of that string portion. |
---|---|
InlineHTML | Calls Inline() to calculate the difference and then transforms its result into a HTML string with
xml<span> tags around each changed portion with class indicating the type of change (del, add, equ or change). |
Full | Diffes two texts by-line. Returns an array; each member has similar form to that of Inline(). |
FullHTML | Calculates difference between two texts by calling Full() and returns a HTML string. Collapses lengthy runs of equal lines and calculates in-line differences with Inline(). Its $options array can have these members:
|
FullHtmlWrapped | Similar to FullHTML() but wraps the entire listing into a
xml<pre> tag, also checking whether or not an input is binary and outputting a message without diffing it if it’s the case. Its $options array can have these members plus all those of FullHTML():
|
HTML-outputting functions convert certain symbols defined in PHPQuickDiff::$htmlReplaces
to more representable text equivalents. Particularly, spaces become middle dots (·), line breaks –
xml<br />
and tabs become two spaces (no ·).
require_once 'quickdiff.php';
echo QuickDiff::FullHtmlWrapped("line1\nline2", "line1\nKABOOM\nline2");
//=> <pre class="qdiff">...</pre>
echo QuickDiff::FullHtmlWrapped("\bin\xA\ry\0u\tput", "line1\nKABOOM\nline2");
//=> <p class="qdiff bin">Diff is unavailable for binary data.</p>
echo QuickDiff::InlineHTML("this plus that", "plus that and this");
//=> <span class="add">this<i>·</i></span>...