• preg_replace() -
This Perl-syntax function is equivalent to the ereg_replace() function. This
function works by replacing all occurrences of the pattern searched with the replacement characters
and then returns the modified result. The fourth parameter is optional, but when a number is entered
it determines how many occurrences of the pattern searched will be replaced. If no number is entered,
all occurrences of the search pattern will be replaced.
<?php
$url = "MySQL http://www.mysql.com";
print preg_replace("/http:\/\/(.*)/","<a
href=\"\${0}\">\${0}</a>",
$url);
?>
The script above changes the http reference to be replaced with the HTML code required to create a
web link. The three components of this function include the pattern to search for ("/http:\/\/(.*)/"), the
replacement string ("<a href=\"\${0}\">\${0}</a>") and then finally the variable that is going to be
searched and replaced. The ${0} tells the preg_replace() function to repeat the complete matched
pattern (in this case http://www.mysql.com).
In addition to individual variables, the pattern and replacement components can also be arrays. The
function will cycle through each element of each array, making replacements as they are found.
<?php
$text = "The dog barks, the bear growls and the cat meows";
$adults = array("/dog/", "/bear/", "/cat/");
$children = array("puppy", "cub", "kitten")
print preg_replace($adults,$children, $text);
?>
Comments
Post a Comment