bluedaniel bluedaniel -5 years ago 115
PHP Question

Simple preg_replace

I cant figure out preg_replace at all, it just looks chinese to me, anyway I just need to remove "

" from a string if its there.

being a number of course, if anyone has a link to a useful
tutorial for beginners that would also be handy!

Answer Source

Actually the basic syntax for regular expressions, as supported by preg_replace and friends, is pretty easy to learn. Think of it as a string describing a pattern with certain characters having special meaning.

In your very simple case, a possible pattern is:


With \d meaning a digit (numeric characters 0-9) and + meaning: Repeat the expression right before + (here: \d) one or more times. All other characters just represent themselves.

Therefore, the pattern above matches any of the following strings:


Since the preg functions use a Perl-compatible syntax and regular expressions are denoted between slashes (/) in Perl, you have to surround the pattern in slashes:

$after = preg_replace('/&page-\d+/', '', $before);

Actually, you can use other characters as well:

$after = preg_replace('#&page-\d+#', '', $before);

For a full reference of supported syntax, see the PHP manual.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download