0

I have the following 2 strings :

orignal string

$orignal_string="Hello world!";

edited string :

$edited_string="Hello Ladies!";

How can I find the diffrence between these two strings, and print the diffrence as Ladies for the given strings?

I am using strcmp() function, but it returns diffrence in numbric value.

 $orignal_string="Hello world!";
$edited_string="Hello Ladies!";
echo strp($orignal_string,$edited_string);

Is there any other way in php or regex to do this?

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • 1
    Did you give a look to https://github.com/sebastianbergmann/diff? It's the component at the core of PHPUnit. – Fabio Mora Dec 20 '15 at 14:46

2 Answers2

1

You can use explode and array_diff_assoc (returns words that differ in this case) or array_intersect_assoc (returns words that are the same in this case) to find different words.

$original_string = "Hello world!";
$edited_string = "Hello Ladies!";

$orig = explode(" ", $original_string);
$edit = explode(" ", $edited_string);

$diff = array_diff_assoc($orig, $edit);
$intersect = array_intersect_assoc($orig, $edit);

echo "diff:\n";
print_r($diff);

echo "intersect:\n";
print_r($intersect);

Output:

diff:
Array
(
    [1] => world!
)
intersect:
Array
(
    [0] => Hello
)

Note that this only works on whole words. If new words are inserted or deleted in the edit string it'd screw the whole thing up though. This is not a fully fledged patchdiff-like approach.

For a unified diff of two string you might want to take a look at xdiff_string_diff.

ccKep
  • 5,786
  • 19
  • 31
1

Here is what you are looking for xdiff_string_diff

Note: This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

Imran Zahoor
  • 2,521
  • 1
  • 28
  • 38
  • This doesn't give you the difference though, which seems to be what OP is looking for. For simply checking if two strings are different there's already `strcmp`, which works faster than doing crc32 twice. – ccKep Dec 20 '15 at 14:27