Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove value from string

Tags:

string

regex

php

If I have a string with IDs

$myIDs = '22,34,445,67889,23';

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

$removeID = '445';

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

preg_replace($removeID, '', $myIDs);

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

$myIDs = '2312,23,234234';

and ID to remove

$removeID = '23';

There's too many potential matches...

like image 607
santa Avatar asked Dec 28 '22 02:12

santa


1 Answers

$array = explode(',',$myIDs);
$array = array_diff($array,array($removeID));
$output = implode(',',$array);
like image 84
fredley Avatar answered Jan 10 '23 13:01

fredley