当前位置: 首页> 函数类别大全> preg_replace_callback_array

preg_replace_callback_array

执行正则表达式搜索并使用回调替换
名称:preg_replace_callback_array
分类:正则处理PCRE
所属语言:php
一句话介绍:给定将表达式与回调函数关联的数组,返回字符串,其中每个表达式的所有匹配项都替换为回调函数返回的子字符串。

定义和用法

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

亲自试一试

同类函数
  • 返回最后一个PCRE正则执行产生的错误代码 preg_last_error

    preg_last_error

    返回最后一个PCRE正则执行产生的错误代
  • 通过一个正则表达式分隔字符串 preg_split

    preg_split

    通过一个正则表达式分隔字符串
  • 执行正则表达式搜索和替换 preg_filter

    preg_filter

    执行正则表达式搜索和替换
  • 执行一个正则表达式的搜索和替换 preg_replace

    preg_replace

    执行一个正则表达式的搜索和替换
  • 执行正则表达式搜索并使用回调替换 preg_replace_callback_array

    preg_replace_callback_array

    执行正则表达式搜索并使用回调替换
  • 执行正则表达式匹配 preg_match

    preg_match

    执行正则表达式匹配
  • 执行一个正则表达式搜索并且使用一个回调进行替换 preg_replace_callback

    preg_replace_callback

    执行一个正则表达式搜索并且使用一个回调进
  • 执行全局正则表达式匹配 preg_match_all

    preg_match_all

    执行全局正则表达式匹配