Reputation: 69
I have the right function, just not finding the right regex pattern to remove (ID:999999) from the string. This ID value varies but is all numeric. I like to remove everything including the brackets.
$string = "This is the value I would like removed. (ID:17937)";
$string = preg_replace('#(ID:['0-9']?)#si', "", $string);
Regex is not more forte! And need help with this one.
Upvotes: 0
Views: 657
Reputation: 47904
Here are two options:
Code: (Demo)
$string = "This is the value I would like removed. (ID:17937)";
var_export(preg_replace('/ \(ID:\d+\)/',"",$string));
echo "\n\n";
var_export(strstr($string,' (ID:',true));
Output: (I used var_export()
to show that the technique is "clean" and gives no trailing whitespaces)
'This is the value I would like removed.'
'This is the value I would like removed.'
Some points:
\d
.strstr()
is an elegant/perfect function.
(space) before ID
to make the output clean.s
or i
modifiers on your pattern, because s
only matters if you use a .
(dot) and your ID
is probably always uppercase so you don't need a case-insensitive search.Upvotes: 0
Reputation: 1217
In PHP regex is in /
and not #
, after that, parentheses are for capture group so you must escape them to match them.
Also to use preg_replace
replacement you will need to use capture group so in your case /(\(ID:[0-9]+\))/si
will be the a nice regular expression.
Upvotes: 0
Reputation: 18741
Try this:
$string = preg_replace('# \(ID:[0-9]+\)#si', "", $string);
You need to escape the parenthesis using backslashes \
.
You shouldn't use quotes around the number range.
You should use +
(one or more) instead of ?
(zero or one).
You can add a space at the start, to avoid having a space at the end of the resulting string.
Upvotes: 1