目录

PHP preg_replace_callback_array() 函数

❮ PHP 正则表达式参考

示例

显示句子中每个单词有多少个字母或数字:

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

function countDigits($matches) {
  return $matches[0] . '[' . strlen($matches[0]) . 'digit]';
}

$input = "There are 365 days in a year.";
$patterns = [
  '/\b[a-z]+\b/i' => 'countLetters',
  '/\b[0-9]+\b/' => 'countDigits'
];
$result = preg_replace_callback_array($patterns, $input);
echo $result;
?>
亲自试一试 »

定义和用法

这个preg_replace_callback_array()函数返回一个字符串或字符串数​​组,其中一组正则表达式的匹配项被替换为回调函数的返回值。

笔记:对于每个字符串,该函数按照给定的顺序评估模式。评估字符串上第一个模式的结果用作第二个模式的输入字符串,依此类推。这可能会导致意外的行为。


语法

preg_replace_callback_array( patterns, input, limit, count)

参数值

Parameter Description
pattern Required. An associative array which associates regular expression patterns to callback functions.

The callback functions have one parameter which is 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 版本: 7+

更多示例

示例

此示例说明了按顺序评估模式可能产生的意外影响。首先,countLetters 替换将 "[4letter]" 添加到 "days",执行替换后,countDigits 替换会在 "4letter" 中查找 "4",并将 "[1digit]" 添加到那:

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

function countDigits($matches) {
  return $matches[0] . '[' . strlen($matches[0]) . 'digit]';
}

$input = "365 days";
$patterns = [
  '/[a-z]+/i' => 'countLetters',
  '/[0-9]+/' => 'countDigits'
];
$result = preg_replace_callback_array($patterns, $input);
echo $result;
?>
亲自试一试 »

❮ PHP 正则表达式参考