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:
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:
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:
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.