悠悠楠杉
网站页面
正文:
在PHP开发中,正则表达式配合回调函数能实现传统替换难以完成的动态逻辑处理。当我们需要根据匹配内容动态决定替换结果时,pregreplacecallback函数便成为解决问题的利器。
标准正则替换使用固定替换字符串:
$text = "用户123 订单456";
$result = preg_replace('/\d+/', '***', $text);
// 输出:用户*** 订单***这种简单替换无法实现诸如"不同前缀的数字需要不同处理"的需求,比如用户ID需要脱敏而订单号需要保留后四位。
通过回调函数可以实现条件逻辑:
function replaceCallback($matches) {
if (strpos($matches[0], '用户') === 0) {
return substr($matches[0], 0, 6).'******';
} elseif (strpos($matches[0], '订单') === 0) {
return substr($matches[0], 0, 6).'****'.substr($matches[0], -4);
}
return $matches[0];
}
$text = "用户123456789 订单987654321";
$pattern = '/(用户\d+|订单\d+)/';
$result = preg_replace_callback($pattern, 'replaceCallback', $text);
// 输出:用户1234****** 订单987****4321str_starts_with()替代strpos()preg_replace_callback_array