note 96029 added to function.preg-replace
| From: | anonymous at osu1 dot php dot net | Date: | Thu, 04 Feb 2010 00:20:06 +0000 |
| Subject: | note 96029 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-165642@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 69.147.83.197
Probable Submitter: 198.144.207.82
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- https://master.php.net/note/edit/96029
Del: integrated -- https://master.php.net/note/delete/96029/integrated
Del: useless -- https://master.php.net/note/delete/96029/useless
Del: bad code -- https://master.php.net/note/delete/96029/bad+code
Del: spam -- https://master.php.net/note/delete/96029/spam
Del: non-english -- https://master.php.net/note/delete/96029/non-english
Del: in docs -- https://master.php.net/note/delete/96029/in+docs
Del: other reasons-- https://master.php.net/note/delete/96029
Reject -- https://master.php.net/note/reject/96029
Search -- https://master.php.net/manage/user-notes.php