Using RegEx to compare two strings for grouped differences in PHP
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 a开发者_StackOverflow中文版rray 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!
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 diff
s using those algoritms.
-- edit 1 Good point from Matt Ball: Highlight the difference between two strings in PHP
$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>";
精彩评论