blazeZ blazeZ - 5 months ago 12
PHP Question

PHP preg_match doesn't match list separated with commas

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,

Answer

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

Comments