note 96029 deleted from function.preg-replace by danbrown
| From: | danbrown@php.net | Date: | Thu, 04 Feb 2010 02:06:08 +0000 |
| Subject: | note 96029 deleted from function.preg-replace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165645@lists.php.net to get a copy of this message | ||
Note Submitter: anonymous
----
The PHP function preg_replace() has powerful functionality in its own right, but extra depth can be
added with the inclusion of the <B>e</B> modifier after the pattern. Take the following
bit of code, which just picks out the letters of a string and replaces them with the letter X.
<?php
$something = 'df1gdf2gdf3sgdfg';
$something = preg_replace("/([a-z]*)/", "X", $something);
echo $something; // XX1XX2XX3XX
?>
This is simple enough, but using the <b>e</b> modifier after the pattern allows us to
use <B>PHP functions</B> within the replace parameters. The following bit of code turns
all letters upper case in a string of random letters by using the strtoupper() PHP function.
<?php
$something = 'df1gdf2gdf3sgdfg';
$something = preg_replace("/([a-z]*)/e", "strtoupper('\\1')",
$something);
echo $something; // DF1GDF2GDF3SGDFG
?>
Here is another example, but in this case the full string is repeated after the modified string.
<?php
$something = 'df1gdf2gdf3sgdfg';
$something = preg_replace("/([a-z0-9]*)/e",
"strtoupper('\\1').'\\1'", $something);
echo $something; // DF1GDF2GDF3SGDFGdf1gdf2gdf3sgdfg
?>
Notice that when using the <b>e</b> modifier it is important to properly escape the
string with single and double quotes. This is because the string as a whole is parsed as PHP and so
if you donât put single quotes around the backreferences then you will get PHP complaining
about constants.