Muhammad
Muhammad

Reputation: 3250

compare 2 strings, subtract the same characters and return the new values

i have two strings, it can be more then two may be 5 or 6

 $a =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123
 $b =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000

i need help i need a function or any way that when i compare $a with $b it should only returns me string like below

$remaining = '2015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';

i tried this function with no luck if (strcmp($var1, $var2) === 0) {

Upvotes: 3

Views: 473

Answers (3)

Andreas
Andreas

Reputation: 23958

You can use str_replace and replace with nothing:

$a =  "2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123";
$b =  "2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000";

Echo str_replace($a, "", $b);

https://3v4l.org/KiZLN

Upvotes: 4

chris85
chris85

Reputation: 23892

An alternative approach here would be to skip the matched content.

$a =  '2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123';
$b =  '2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';
if(strpos($b, $a) !== false) {
    echo substr($b, (strrpos($b, $a) + strlen($a)));
}

would work. If you have multiple matches though you will need a different approach (because this is only for 1 iteration). The str_replace is probably your best approach.

Demo: https://eval.in/829490

Upvotes: 1

Don't Panic
Don't Panic

Reputation: 41810

It might not seem obvious the way you're thinking of it, but str_replace should work for this.

$remaining = str_replace($a, '', $b);

If $a is found in $b then $remaining will be $b with the characters of $a removed from it, otherwise $remaining will be the unchanged value of $b.

Upvotes: 5

Related Questions