写给愿意动手的 PHP 开发者
PHP学习网 PHP学习网
公告PHP学习网为公益性网站,致力于为广大PHP爱好者服务
首页/ PHP 函数大全/ 正则表达式/ preg_replace_callback()
正则表达式 PHP PHP 4.0.5 preg_replace_callback

preg_replace_callback()

用回调函数的返回值做替换,适合需要计算的场景。

preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0): string|array|null

参数

参数类型说明
$patternstring|array正则
$callbackcallable接收匹配数组,返回替换字符串
$subjectstring|array被处理的字符串
$limitint最多替换几次

返回值

string|array|null — 替换后的结果。

示例

PHP
$text = '订单 20261121 已发货';
echo preg_replace_callback('/\d{8}/', function ($m) {
    return substr($m[0], 0, 4) . '年' . substr($m[0], 4, 2) . '月';
}, $text);
输出
订单 2026年11月 已发货

注意

  • 回调返回 null 表示跳过该处替换。
  • 比 preg_replace 的 /e 修饰符安全得多,后者已在 PHP 7 移除。

相关函数