views:

1416

answers:

3

I have 2 strings that I'd like to compare, and return the positions of the different characters in the second string. For instance, if I have 1. "The brown fox jumps over the lazy dog" and 2. "The quick brown fox jumped over the lazy dog", I want it to highlight "quick" and "ed". What's the best way to go about this in PHP?

+2  A: 

The algorithm you're looking for is the "longest common substring problem". From there it is easy to determine the differences. See Wikipedia:

http://en.wikipedia.org/wiki/Diff#Algorithm

Thomas
+2  A: 

This is going to give you a headache unless you define your porblem more clearly to start! Let's assume that str1 is "Amanda and Amy", and str2 is "Amanda and Amylase Amy".

Is your function to return "lase Amy" or "Amylase "?

Properly defining your problem is the first step towards a solution!

William Keller
It doesn't matter in this case. Both solutions would mean the original was changed and it would show the change. I would assume returning "lase Amy" would be easier since the original string is unbroken and at the start of the second string.
David
+3  A: 

This might do the trick:

PHP Inline Diff

Text_Diff

Terhorst