Home > Article > Backend Development > php mixed preg_replace_callback example application code_PHP tutorial
php tutorial mixed preg_replace_callback example application code
//Requirement: Add a request=xxx after all connections; This function is more flexible than preg_replace. Please note that the content it replaces is the content of the entire regular expression.
$content = 'http://www.bkjia.com/aaa.php?id=111">Link 2';
function add_source($matches)
{
If(strpos($matches[1], '?'))
{
return 'href="'.$matches[1].'&request=xxx"'; //Note that things outside the regular brackets are added here and below: href="
}
else
{
return 'href="'.$matches[1].'?request=xxx"';
}
}
$content = preg_replace_callback('/href=['|"](.*?)['|"]/', 'add_source', $content);
//Example 2
// This text is for 2002,
// Now want to make it available for 2003
$text = "april fools day is 04/01/2002n";
$text.= "last christmas was 12/24/2001n";
// Callback function
function next_year($matches) {
// Normally: $matches[0] is the complete match
// $matches[1] is the match for the subpattern in the first bracket
// And so on
Return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(d{2}/d{2}/)(d{4})|",
“next_year”,
$text);
// The result is:
// April fools day is 04/01/2003
// last christmas was 12/24/2002