PHP preg_replace_callback_array() 函数

定义和用法

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

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

实例

例子 1

展示一个句子中每个单词包含多少字母或数字:

<?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;
?>

亲自试一试

例子 2

此例说明了按顺序评估模式可能产生的潜在意外效果。首先,countLetters 替换会在 "days" 后添加 "[4letter]",执行该替换后,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;
?>

亲自试一试

语法

preg_replace_callback_array(patterns, input, limit, count)
参数 描述
pattern

必需的。关联数组,将正则表达式模式与回调函数相关联。

回调函数有一个参数,它是一个匹配数组。

数组的第一个元素包含整个表达式的匹配项,而剩余的元素则包含表达式中每个组的匹配项。

input 必需。要执行替换的字符串或字符串数组。
limit

可选。默认为 -1,表示无限制。

设置每个字符串中可以进行的替换次数。

count 可选。函数执行后,此变量将包含一个数字,指示已执行的替换次数。

技术细节

返回值: 返回一个字符串或字符串数组,这是将替换应用于输入字符串或字符串数组的结果。
PHP 版本: 7+