1

So I have two strings, and I want to compare and return the differences. I don't think I can use a simple preg_match() since it returns an array of all differences.

I'm having a little trouble explaining myself but I hope the following example clears it up:

So I have

String 1: AA **B** AA
String 2: AA **DA** AA

I want the return to be something similar to:

String2: 2 ==> DA

Basically I'm trying to examine the relationship between the position of B in String1 and DA in String 2

Any kind of direction would be really appreciated, Thanks!

bensiu
  • 24,660
  • 56
  • 77
  • 117
Aksr
  • 13
  • 3
  • You're trying to write `diff` using regex? http://stackoverflow.com/questions/321294/highlight-the-difference-between-two-strings-in-php – Matt Ball Apr 16 '11 at 21:32

2 Answers2

1

Actually, regex won't do this for you. You can read how diff works on http://en.wikipedia.org/wiki/Diff#Algorithm (that's what you want). You can create a function or class that does simple diffs using those algoritms.

-- edit 1 Good point from Matt Ball: Highlight the difference between two strings in PHP

Community
  • 1
  • 1
Rudie
  • 52,220
  • 42
  • 131
  • 173
  • Thanks guys! Just going to repost the archived link from Matt's comment: http://web.archive.org/web/20080506155528/http://software.zuavra.net/inline-diff/ – Aksr Apr 16 '11 at 21:38
0
$stringA = "hello world hello world helloo world";
$stringB = "hello php hello php hello php";

echo "string 1---->".$stringA."<br>";
echo "string 2---->".$stringB."<br>";

$array1 = explode(' ', $stringA);
$array2 = explode(' ', $stringB);

$result = array_diff($array2, $array1);

$zem= implode(' ',$result);
if (!empty($zem)) {
    echo "string diffrence---> ".$zem."<br>";
} else {
    echo "string diffrence--->both strings are same <br>";
}

$a = count(explode(' ', $stringA));
$b= count(explode(" ", $zem));

similar_text($stringA, $stringB , $p);
echo "  similarity between  the stirng is  Percent:".$p."% <br>";
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
Umer Singhera
  • 95
  • 2
  • 11