PHP Tutorials Mixed Preg_replace_callback Instance application code
Requirements: Add a request=xxx after all connections; This function is more flexible than preg_replace, and note that it replaces the contents of the entire regular expression.
$content = ' <a href= ' http://www.jzread.com/aaa.php ' > Link 1</a><a href= ' http://www.jzread.com/aaa.php? id=111 "> Link 2</a>";
function Add_source ($matches)
{
if (Strpos ($matches [1], '? '))
{
Return ' href= '. $matches [1]. ' &request=xxx "'; Note that here and below are the things that are outside the regular brackets: href=.
}
Else
{
Return ' href= '. $matches [1]. Request=xxx "';
}
}
$content = Preg_replace_callback ('/href=[' |) (.*?) ['|"] /', ' Add_source ', $content);
Example Two
This text is used for 2002 years,
Now want to make it available for 2003
$text = "April Jesters day is 04/01/2002n";
$text. = "Last Christmas was 12/24/2001n";
callback function
function Next_year ($matches) {
Typically: $matches [0] is a complete match
$matches [1] is a match for the child pattern in the first parenthesis
So
return $matches [1]. ($matches [2]+1);
}
Echo Preg_replace_callback (
"| (d{2}/d{2}/) (D{4}) | ",
"Next_year",
$text);
The results are:
April Jesters Day is 04/01/2003
Last Christmas was 12/24/2002