Prev | Current Page 312 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

";
echo preg_quote($text);
?>
This returns the following:
Tickets for the bout are going for \$500\.
Replacing All Occurrences of a Pattern
The preg_replace() function operates identically to ereg_replace(), except that it
uses a Perl-based regular expression syntax, replacing all occurrences of pattern with
replacement, and returning the modified result. Its prototype follows:
mixed preg_replace(mixed pattern, mixed replacement, mixed str [, int limit])
The optional input parameter limit specifies how many matches should take place.
Failing to set limit or setting it to -1 will result in the replacement of all occurrences.
Consider an example:
$text = "This is a link to http://www.wjgilmore.com/.";
echo preg_replace("/http:\/\/(.*)\//", "\${0}", $text);
?>
This returns the following:
This is a link to
http://www.wjgilmore.com/.
Interestingly, the pattern and replacement input parameters can also be arrays.
This function will cycle through each element of each array, making replacements
as they are found. Consider this example, which could be marketed as a corporate
report filter:
246 CHAPTER 9 ?–  STRINGS AND REGULAR EXPRESSIONS
$draft = "In 2007 the company faced plummeting revenues and scandal.";
$keywords = array("/faced/", "/plummeting/", "/scandal/");
$replacements = array("celebrated", "skyrocketing", "expansion");
echo preg_replace($keywords, $replacements, $draft);
?>
This returns the following:
In 2007 the company celebrated skyrocketing revenues and expansion.


Pages:
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324