Приглашаем посетить
Высоцкий (vysotskiy-lit.ru)

Section 15.6.  Regular Expression Replacements

Previous
Table of Contents
Next

15.6. 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 passwe 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 the replacement has taken place. Consider this script:

    $a = "Foo moo boo tool foo";
    $b = preg_replace("/[A-Za-z]oo\b/e", 'strtoupper("$0")', $a);
    print $b;

This time, PHP will replace each match with strtoupper("word") and, because we have appended an e (for "eval" or "execute") to the end of our regular expression, PHP will execute the replacements it makes. That is, it will take strtoupper(word) and replace it with the result of the strtoupper( ) function, which is, of course, WORD. It is essential to put the $0 inside double quotes so that it is treated as a stringwithout the quotes, it will just read strtoupper(foo), which is probably not what you meant.

Here is the output:

    FOO MOO BOO tool FOO

Optionally you can also pass a fourth parameter to preg_replace( ) to specify the maximum number of replacements you want to make. For example:

    $a = "Foo moo boo tool foo";
    $b = preg_replace("/[A-Za-z]oo\b/e", 'strtoupper("$0")', $a, 2);
    print $b;

Now the output is this:

    FOO MOO boo tool foo

Only the first two matches have been replaced, thanks to the fourth parameter being set to 2.


Previous
Table of Contents
Next