Regular Expression Replacements

Using regular expressions to accomplish string replacement is done with the function preg_replace(), and works in much the same way as preg_match().

The preg_replace() function takes a regexp as parameter one, what it should replace each match with as parameter two, and the string to work with as parameter three. The second parameter is plain text, but can contain $n to insert the text matched by subpattern n of your regexp rule. If you have no subpatterns, you should use $0 to use the matched text, like this:

    $a = "Foo moo boo tool foo";
    $b = preg_replace("/[A-Za-z]oo\b/", "Got word: $0\n", $a);
    print $b;

That script would output the following:

    Got word: Foo
    Got word: moo
    Got word: boo
    tool Got word: foo

If you are using subpatterns, $0 is set to the whole match, then $1, $2, and so on are set to the individual matches for each subpattern. For example:

    $match = "/the (car|cat) sat on the (drive|mat)/";
    $input = "the cat sat on the mat";
    print preg_replace($match, "Matched $0, $1, and $2\n", $input);

In that example, $0 will be set to "the cat sat on the mat", $1 will be "cat", and $2 will be "mat".

There are two further uses for preg_replace() that are particularly interesting: first, you can pass arrays as parameter one and parameter two, and preg_replace() will perform multiple replaces in one pass—we will be looking at that later. The other interesting functionality is that you can instruct PHP that the match text should be executed as PHP code once ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.