说明
mixed
preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit] )
本函数的行为几乎和
preg_replace() 一样,除了不是提供一个
replacement 参数,而是指定一个
callback 函数。该函数将以目标字符串中的匹配数组作为输入参数,并返回用于替换的字符串。
例子 1. preg_replace_callback() 例子 |
<?php
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
function next_year($matches) {
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);
?>
|
|
You'll often need the callback function
for a preg_replace_callback() in just one place.
In this case you can use create_function() to
declare an anonymous function as callback within the call to
preg_replace_callback(). By doing it this way
you have all information for the call in one place and do not
clutter the function namespace with a callback functions name
not used anywhere else.
例子 2. preg_replace_callback() 和 create_function() |
<?php
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
$line = fgets($fp);
$line = preg_replace_callback(
'|<p>\s*\w|',
create_function(
'$matches',
'return strtolower($matches[0]);'
),
$line
);
echo $line;
}
fclose($fp);
?>
|
|
参见 preg_replace() 和
create_function()。