Page 597 - Beginning PHP 5.3
P. 597
Chapter 18: String Matching with Regular Expressions
$replacements = array(
“[PRICE CENSORED]”,
“[DATE CENSORED]”
);
echo preg_replace( $patterns, $replacements, $text );
This script displays:
The wholesale price is [PRICE CENSORED]. The product will be released on
[DATE CENSORED].
If your replacements array contains fewer elements than your expressions array, matched text for any
expression without a corresponding replacement is replaced with an empty string. For example:
$text = “The wholesale price is $89.50. “ .
“The product will be released on Jan 16, 2010.”;
$patterns = array(
“/\\$\d+\.\d{2}/”,
“/\w{3} \d{1,2}, \d{4}/”
);
$replacements = array(
“[PRICE CENSORED]”
);
echo preg_replace( $patterns, $replacements, $text );
displays:
The wholesale price is [PRICE CENSORED]. The product will be released on .
preg_replace() supports two more optional arguments. The first argument, an integer, lets you restrict
how many times the pattern (or patterns) is replaced in the target string (or strings):
// Displays “71%, 83%”
echo preg_replace( “/\d+\%(,| )*/”, “”, “14%, 59%, 71%, 83%”, 2 );
This pattern replaces a percentage figure (followed optionally by commas and spaces) with an empty
string. Because a limit argument of 2 was supplied, only the first two matches are replaced.
The second optional argument is a variable to hold the number of replacements performed. (If you want
to use this argument but you don ’ t want to limit the number of replacements, pass – for the previous
1
argument.) The following example replaces the character ‘ % ’ with the string “ percent ” four times, and
displays the number of replacements:
preg_replace( “/\%/”, “ percent”, “14%, 59%, 71%, 83%”, -1, $count );
echo $count; // Displays “4”
The number stored in $count is the total number of replacements performed. So if you pass an array of
10 target strings and text is replaced once in five of them, then $count equals 5.
559
9/21/09 6:17:59 PM
c18.indd 559 9/21/09 6:17:59 PM
c18.indd 559