Top Results
Top Results

Reputation: 69

Looking to use preg_replace to remove characters from my strings

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

Answers (3)

mickmackusa
mickmackusa

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:

  • Regex is a better / more flexible solution if your ID substring can exist anywhere in the string.
  • Your regex pattern doesn't need a character class if you use the shorthand range character \d.
  • Regex generally speaking should only be used when standard string function will not suffice or when it is proven to be more efficient for a specific case.
  • If your ID substring always occurs at the end of the string, strstr() is an elegant/perfect function.
  • Both of my methods write a (space) before ID to make the output clean.
  • You don't need either 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

Nathanael Demacon
Nathanael Demacon

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

MikO
MikO

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

Related Questions