preg_replace_callback
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
preg_replace_callback - 执行正则表达式搜索并使用回调进行替换
描述
mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )
这个函数的行为几乎和preg_replace()是一样的,除了替换参数,应该指定一个回调函数。
参数
pattern
要搜索的模式。它可以是字符串,也可以是字符串数组。
callback
将被调用并在主题字符串中传递匹配元素数组的回调函数。 回调应该返回替换字符串。 这是回调:
string handler ( array $matches )
您经常只需要一个位置的preg_replace_callback()回调函数。 在这种情况下,您可以使用匿名函数在调用preg_replace_callback()的过程中声明回调。 通过这样做,您可以在一个地方获得所有调用的信息,并且不会在其他地方没有使用回调函数名称的情况下混淆函数名称空间。
示例#1 preg_replace_callback()和匿名函数
<?php
/*?a?unix-style?command?line?filter?to?convert?uppercase
?*?letters?at?the?beginning?of?paragraphs?to?lowercase?*/
$fp?=?fopen("php://stdin",?"r")?or?die("can't?read?stdin");
while?(!feof($fp))?{
????$line?=?fgets($fp);
????$line?=?preg_replace_callback(
????????'|<p>\s*\w|',
????????function?($matches)?{
????????????return?strtolower($matches[0]);
????????},
????????$line
????);
????echo?$line;
}
fclose($fp);
?>
subject
用字符串搜索和替换的字符串或数组。
limit
每个主题字符串中每种模式的最大可能替代数。 默认为-1(没有限制)。
count
如果指定,则此变量将填充完成的替换次数。
返回值
preg_replace_callback()返回一个数组,如果subject参数是一个数组,否则返回一个字符串。 出错时返回值为NULL
如果找到匹配项,则将返回新的主题,否则主题将不变。
更新日志
版 | 描述 |
---|---|
5.1.0 | 计数参数已添加 |
例子
示例#2 preg_replace_callback()示例
<?php
//?this?text?was?used?in?2002
//?we?want?to?get?this?up?to?date?for?2003
$text?=?"April?fools?day?is?04/01/2002\n";
$text.=?"Last?christmas?was?12/24/2001\n";
//?the?callback?function
function?next_year($matches)
{
??//?as?usual:?$matches[0]?is?the?complete?match
??//?$matches[1]?the?match?for?the?first?subpattern
??//?enclosed?in?'(...)'?and?so?on
??return?$matches[1].($matches[2]+1);
}
echo?preg_replace_callback(
????????????"|(\d{2}/\d{2}/)(\d{4})|",
????????????"next_year",
????????????$text);
?>
上面的例子将输出:
April fools day is 04/01/2003
Last christmas was 12/24/2002
示例#3 preg_replace_callback()使用递归结构来处理封装的BB代码
<?php
$input?=?"plain?[indent]?deep?[indent]?deeper?[/indent]?deep?[/indent]?plain";
function?parseTagsRecursive($input)
{
????$regex?=?'#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';
????if?(is_array($input))?{
????????$input?=?'<div?style="margin-left:?10px">'.$input[1].'</div>';
????}
????return?preg_replace_callback($regex,?'parseTagsRecursive',?$input);
}
$output?=?parseTagsRecursive($input);
echo?$output;
?>
扩展内容
- preg_replace_callback_array() - 执行正则表达式搜索并使用回调进行替换
- preg_quote() - 引用正则表达式字符
- preg_replace() - 执行正则表达式搜索并替换
- preg_last_error() - 返回上一次PCRE正则表达式执行的错误代码
- 匿名功能
- 有关回调类型的信息
← preg_replace_callback_array
preg_replace →
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com