David
David

Reputation: 146

How do you find the difference between 2 strings in PHP?

I have 2 strings that I'd like to compare, and return the positions of the different characters in the second string.

For example, if I have

  1. "The brown fox jumps over the lazy dog"
  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?

Upvotes: 4

Views: 5179

Answers (3)

Terhorst
Terhorst

Reputation: 2181

This might do the trick:

PHP Inline Diff

Text_Diff

Upvotes: 3

William Keller
William Keller

Reputation: 5410

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!

Upvotes: 2

Thomas
Thomas

Reputation: 181785

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

Upvotes: 2

Related Questions