What is the easiest way to highlight the difference between two strings in PHP?
I'm thinking along the lines of the Stack Overflow edit history page, where new text is in green and removed text is in red. If there are any pre-written functions or classes available, that would be ideal.
I came across this PHP diff class by Chris Boulton based on Python difflib which could be a good solution:
PHP Diff Lib
Here is a short function you can use to diff two arrays. It implements the LCS algorithm:
It generates two arrays:
If you populate an array with characters, it can be used to compute inline difference. Now just a single step to highlight the differences:
Eg.:
Will output:
S
tackOerverfFaulowtAdditional notes:
There is also a PECL extension for xdiff:
In particular:
Example from PHP Manual:
This is the best one I've found.
http://code.stephenmorley.org/php/diff-implementation/
I would recommend looking at these awesome functions from PHP core:
similar_text — Calculate the similarity between two strings
http://www.php.net/manual/en/function.similar-text.php
levenshtein — Calculate Levenshtein distance between two strings
http://www.php.net/manual/en/function.levenshtein.php
soundex — Calculate the soundex key of a string
http://www.php.net/manual/en/function.soundex.php
metaphone — Calculate the metaphone key of a string
http://www.php.net/manual/en/function.metaphone.php
If you want a robust library, Text_Diff (a PEAR package) looks to be pretty good. It has some pretty cool features.