Remove value from row

If I have a line with identifiers

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

and I’m assigned a value, how to remove it from the string, if I know for sure what is it in the string?

 $removeID = '445'; 

Am I using user preg_replace or is there a better method? For example, if it is in the middle of the line, and I delete only the value, I get two commas, and then I need to replace them with one comma?

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

UPDATE: These are all great deals. However, I just thought of one potential problem. This probably needs to be treated as an array instead of a regular expression. Which my line looks like this:

 $myIDs = '2312,23,234234'; 

and identifier for deletion

 $removeID = '23'; 

Too many potential matches ...

+4
source share
7 answers
 $array = explode(',',$myIDs); $array = array_diff($array,array($removeID)); $output = implode(',',$array); 
+3
source

You can use regex:

 $remove = preg_quote($removeID, '/'); $regex = '/,'.$remove.'$|^'.$remove.',|^'.$remove.'$|,'.$remove.'(?=,)/'; $myIDs = preg_replace($regex, '', $myIDs); 

Which basically says: replace $removeID , where it is prefixed either with the beginning of the line, or with a comma and suffixes, either with the end of the line, or with another comma.

Edit: I changed the regular expression to the tested regular expression (I tested all the features and seemed to work in all cases that I can think of) ...

+3
source

Here is the regular expression to do the job for element "89":

 /(^|,)89(?=,|$)/ 

It matches ", 89" (or simply "89" if it is at the beginning of the input) if it is executed directly by either another "," or the end of the input.

With proper shielding and some abstraction:

 <?php $myIDs = '23,45,678967,89,12'; $toRemove = 89; $myIDs = preg_replace('/(^|,)' . preg_quote($toRemove) . '(?=,|$)/', '', $myIDs); ?> 

Tested with multiple inputs.

Hope this helps!

+2
source
 $myIDs = '1,2,3,4,5'; $remID = '5'; $myIDs = preg_replace(array("/^$remID,|(?:,|^)$remID$/","/,$remID,/"), array('',','), $myIDs); 

Perfect link

+1
source
 $myarray=explode(',', $myIDs) $excluded=preg_grep('^' . $removeID . '$', $myarray, PREG_GREP_INVERT) $newId=join(',', $excluded) 
+1
source

I also want to use the solution:

 preg_replace( '/\b(,' . $rID . '|' . $rID . ',|' . $rID . ')\b/', '', $myIDs ); 

i.e.

 preg_replace( '/\b(,445|445,|445)\b/', '', $myIDs ); 

( example )

+1
source

The easiest way:

 $myIDs = '22,34,445,67889,23'; $removeID = 445; $myIDs = preg_replace("/($removeID,|,$removeID)/", '', $myIDs); 

Update

 $myIDs = preg_replace("/(^$removeID,|,$removeID$|,$removeID(?=,))/", '', $myIDs); 
-1
source

Source: https://habr.com/ru/post/1336591/


All Articles