Search code examples
phphighlightingstring-comparison

compare and highlight difference of two strings containing html in php


I'm trying to compare two string in PHP which both contain HTML. (they are both placed into a database via a wysiwyg editor).

The result I want to get is to see which words are removed and which ones have been added.

To do this I'm using this bit of code as follows:

$old = "<p>Lorem ipsum is standard dummy text</p>";
$new = "<p>Lorem ipsum was standard dummy jibbrish</p>";
echo htmlDiff($old, $new);

which works perfectly fine. However when I add some tags such as <li>, the fun ends.

For example if I would have the following:

$old = "<p>Lorem ipsum is standard dummy text. <ul><li>Lorem</li><li>Ipsum</li><li>Dolor</li></ul></p>";

$new = "<p>Lorem ipsum was standard dummy jibbrish. <ul><li>Lorem</li><li>Dolor</li></ul></p>";

echo htmlDiff($old, $new);

The <del> tag gets added correctly after the first list item, but the removed list item gets placed outside of the <del> tag, making it look like it was not removed.

I could resolve this by stripping all tags, but I would like to keep the layout of both strings.

Any help or suggestions are greatly appreciated.


Solution

  • You could try one of the following alternatives to the htmlDiff function:

    1. PHP inline dif mini-library which produces results like this
    2. Horde_Text_Diff library
    3. xdiff_string_diff function from xdiff extension