PHP 7 中的 Preg_replace_callback_array()
phpserver side programmingprogramming更新于 2025/8/30 19:37:17
PHP 7 中的 Preg_replace_callback_array() 函数表示正则表达式,并替代了回调函数的使用。此函数返回一个字符串或一个字符串数组,用于匹配一组正则表达式,并使用回调函数替换它们。
语法
preg_replace_callback_array(patterns, input, limit, count)
参数值:
- pattern − 它需要一个关联数组,用于将正则表达式模式与回调函数关联起来。
- input/subject − 它需要一个字符串数组来执行替换。
- limit − 它是可选的。默认值为 -1,表示无限制。它限制了每个字符串中可以进行的替换次数。
- count −与 limit 一样,它也是可选的。此变量包含一个数字,表示函数执行后执行了多少次替换。
- flags −它可以是 preg_offset_capture 和 preg_unmatched_as_null 标志的组合,这些标志会影响匹配数组的格式。
- 返回值 −preg_replace_callback_array() 返回一个字符串或一个字符串数组。如果发现错误,则返回 null 值。如果找到匹配项,则返回新的主题,否则,将不加更改地返回主题。
Preg_replace_callback_array():示例
<html>
<head>
<title> PHP 7 Featuretutorialpoint:</title>
</head>
<body>
<?php
$subject = 'AaaaaaaBbbbCccc';
preg_replace_callback_array (
[
'~[a]+~i' => function ($match) {
echo strlen($match[0]), ' number of "a" found', PHP_EOL;
},
'~[b]+~i' => function ($match) {
echo strlen($match[0]), ' number of "b" found', PHP_EOL;
},
'~[c]+~i' => function ($match) {
echo strlen($match[0]), ' number of "c" found', PHP_EOL;
}
],
$subject
);
?>
</body>
</html>
输出
上述程序代码的输出是 −
7 number of "a" found 4 number of "b" found 5 number of "c" found

