Hudzilla.org - the homepage of Paul Hudson
Contents > Functions > Regular expressions Wish List | Report Bug | About Me ]

4.8.5     Regular expression replacements: preg_replace()

This is NOT the latest copy of this book; click here for the latest version.

mixed preg_replace ( mixed pattern, mixed replacement, mixed input [, int limit])

You've already done the hardest part in regexps by learning the patterns and how to write your own expressions - it is all easy going now.

Using regular expressions to accomplish string replacement is done with the function preg_replace(), and works much in the same way as preg_match(). Also as with preg_match(), preg_replace() is substantially slower than str_replace() for basic operations and should be avoided when possible.

Preg_replace() takes a regexp as its first parameter, what it should replace each match with as parameter two, and the string to work with as the third parameter. The second parameter is plain text, but can contain $n to insert the text matched by part n of your regexp rule. Unless you are writing complicated multi-part regexps, you will want to use $0 to use the matched text, like this:

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

That script would output the following:

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

There are two further uses for preg_replace() that are particularly interesting: firstly, you can pass arrays as parameter one and parameter two, and preg_match() will perform multiple replaces in one pass - we will be looking at that later. The other interesting piece of 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:

<?php
    $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 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 . Note that it is essential to put the $0 inside double quotes so that it is treated as a string - without 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:

<?php
    $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

As you can see, only the first two matches have been replaced, thanks to the fourth parameter being set to 2.

That brings us to the end of this long section on regular expressions. Hopefully you will see that you can accomplish most of your tasks with a selection of very simple expressions, but that if you want more power it is certainly just there waiting for you.





<< 4.8.4 Guru regexps   4.8.6 Regular expression syntax examples >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 05 Dec 2008

Hi, people!
I need a help.

PHP code:

$product_name = 'box';
$string = "The price of %CHANGE% is $0,5 just now!";

%CHANGE% - should be hanged, and when I do the next:

$result = preg_replace("/%CHANGE%/", $product_name, $string);
returs $result : The price of box is %CHANGE%,5 just now!

I understand why it is, but how can I turn $0 off?
When I use str_replace I get:
The price of box is ,5 just now! $0 - disappears!!

Gogo the Great, Kingstown, Serbia - 05 Dec 2008

Quote:

"Note that it is essential to put the $0 inside double quotes so that it is treated as a string - without the quotes, it will just read strtoupper(foo), which is probably not what you meant."

I've tried to put $0 without double qoutes, like this:

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

and it worked perfectly well, meaning that it produced the very same output as with the double quotes! Btw, I'm using PHP 5.0 ;)

Tom - 05 Dec 2008

There is also an [int &count] parameter to preg_replace.

Unix Programmer - 05 Dec 2008

"The second parameter is plain text, but can contain $n to insert the text matched by part n of your regexp rule."

It would be nice if you had a section about how to break your regular expressions down into parts. It's not very difficult, could easily be done with simple examples and is extremely useful.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is seven plus one?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow