tags:

views:

37

answers:

2

Hi,

I have a string that is

$str = "testingSUB1";

How can I strip out SUB* from the string? I assume using preg_replace but I'm not good with matching what I want with regex.

Does anyone know how I can do this?

Thank you

+2  A: 

That's the way.

$str = preg_replace("#SUB[0-9]+#", "", $str);

The #s are delimiters; they can be any non-alphanumeric/whitespace/backslash character that doesn't appear in the pattern. [0-9] means any digit (you can use \d too in some languages, but I usually don't bother), and the + means one or more of the previous, so if you take the + out it will only replace the first digit

Michael Mrozek
+1 - But why # instead of / ?
Ben
I got in the habit of using # because it rarely comes up in the pattern, whereas / shows up all the time (in URLs or Linux paths, for example). / will work though
Michael Mrozek
Always use `'` whenever possible in place of `"` also `+ means any number of the previous` is incorrect it means `one or more`
gameover
I fixed the definition of `+`, but as for the quotes, if you're so concerned about performance that you're actually shaving off a few milliseconds using `'` instead of `"`, you're programming in the wrong language
Michael Mrozek
+2  A: 

This should do it:

$word = 'SUB';
$string = 'testingSUB1';

echo preg_replace('~^(.*?)(' . preg_quote($word, '~') . '\d+)(.*?)$~', '$1$2', $string);

EDIT - This is better:

echo preg_replace('~' . preg_quote($word, '~') . '\d+~', '', $string);
Alix Axel
+1 for preg_quote. Didn't know about that function.
Mark