Reputation:
Here's my users list
james,john,mark,luke,
james,john,mark,luke,mary,david
I want to remove the repeated part and retain the remaining.
So here's my code
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
// Replace , with |
$expr = rtrim(preg_replace('/\,/', '|', $old), '|');
$newstr = preg_replace("/$expr/i", '', $users);
echo $newstr;
Output
,,,,mary,david
I want
mary,david,
Upvotes: 1
Views: 119
Reputation: 43574
A solution, based on your code using trim
:
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
$expr = rtrim(preg_replace('/\,/', '|', $old), '|');
$newstr = preg_replace("/$expr/i", '', $users);
echo trim($newstr, ',');
Demo: https://3v4l.org/W3XKe
A better solution using explode
, array_diff
and implode
:
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
$old_items = explode(',', $old);
$users_items = explode(',', $users);
echo implode(array_diff($users_items, $old_items), ',');
Demo: https://3v4l.org/tnt9F
Upvotes: 2
Reputation: 24555
Can't test it right now, but wouldn't it work simply like that?
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
echo preg_replace("/$old/", "", $users); //should print "mary,david"
Upvotes: 0