目录

PHP preg_replace_callback() 函数

❮ PHP 正则表达式参考

示例

计算句子中所有单词的字母数:

<?php
function countLetters($matches) {
  return $matches[0] . '(' . strlen($matches[0]) . ')';
}

$input = "Welcome to 91xjr.com!";
$pattern = '/[a-z0-9\.]+/i';
$result = preg_replace_callback($pattern, 'countLetters', $input);
echo $result;
?>
亲自试一试 »

定义和用法

这个preg_replace_callback()给定一个表达式和一个回调,函数返回一个字符串,其中表达式的所有匹配项都被回调函数返回的子字符串替换。


语法

preg_replace_callback( pattern, callback, input, limit, count)

参数值

Parameter Description
pattern Required. A regular expression or array of regular expressions indicating what to search for
replacements Required. A callback function which returns the replacement.

The callback function has one parameter containing an array of matches. The first element in the array contains the match for the whole expression while the remaining elements have matches for each of the groups in the expression.
input Required. The string or array of strings in which replacements are being performed
limit Optional. Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string
count Optional. After the function has executed, this variable will contain a number indicating how many replacements were performed

技术细节

返回值: 返回将替换应用于输入字符串或多个字符串所产生的字符串或字符串数​​组。
PHP 版本: 4.0.5+
变更日志: PHP 5.1.0 - 添加了 count 参数

❮ PHP 正则表达式参考