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 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!




Actually, regex won't do this for you. You can read howdiff works on (that's what you want). You can create a function or class that does simplediffs 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>";

People are also looking for solutions to the problem: php - How to random salt for SHA512


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.