Simple preg_replace

26,709

Solution 1

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:

&page-\d+

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:

&page-0
&page-665
&page-1234567890

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.

Solution 2

preg_replace uses Perl-Compatible Regular Expression for the search pattern. Try this pattern:

preg_replace('/&page-\d+/', '', $str)

See the pattern syntax for more information.

Solution 3

$outputstring = preg_replace('/&page-\d+/', "", $inputstring);

preg_replace()

Share:
26,709
bluedaniel
Author by

bluedaniel

Created my own recipe search during uni that gives you ideas based on what ingredients you have lying around. The Guardian newspaper bought it and now I work freelance for them pretty much full time.

Updated on June 20, 2020

Comments

  • bluedaniel
    bluedaniel almost 4 years

    I cant figure out preg_replace at all, it just looks chinese to me, anyway I just need to remove "&page-X" from a string if its there.

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

  • bluedaniel
    bluedaniel over 14 years
    so what if I wanted to replace "/page-1"