tags:

views:

1453

answers:

7

Are there any libraries (3rd party or built-in) in PHP to calculate text diffs?

+3  A: 

it depends exactly what you mean and what you want to do but there is

PEAR Text_Diff - Engine for performing and rendering text diffs

Alister Bulman
+4  A: 

What sort of diffs? File diffs? There is array_diff() which acts on arrays. Then there is also xdiff, which "enables you to create and apply patch files containing differences between different revisions of files.". The latter acts on files or strings.

Edit: I should add xdiff doesn't appear to be out in a release yet. You have to build from source to use it.

Jonah Braun
Thanks for the answer - i've clarified the question a bit now.
nickf
"xdiff doesn't appear to be out in a release yet" -- bugger.
nickf
+1  A: 

It really depends on what outcome you want. If all you want to do is to get the diff files for two sets of text, you may find it simpler to just use an external diff command (which of course totally depends on the environment you're developing for).

$diff = `diff $file1 $file2`;

From there if you want to use the diff information at all you would need to parse and this solution might not be what you're after. In that case I'd suggest looking at the PEAR library mentioned above or searching for a similar text parsing library.

Mathew Byrne
and of course, this means you have to be very careful to vet your user input to make sure the command is working on the right files and cannot be made to look up the wrong files.
DGM
Use `escapeshellarg` when using string concatenation to create a shell command.
troelskn
+1  A: 

MediaWiki's diff engine is open source (just like the rest of it). If you like the way Wikipedia handles text diffs, it may be a solution for you.

ceejayoz
A: 

I really like this JavaScript based one for web projects.

http://snowtide.com/jsdifflib

Lou Franco
A: 

The output of this is in GNU diff format. It might be what you're looking for.

mlambie
A: 

There is a nice and tiny Simplediff project on Github which creates text and HTML diffs.

takeshin
i didn't run the program, but it appears that it is for array differences?
nickf
@nickf Yes, but you can explode the text into arrays easily.
takeshin