Deprecated: preg_replace(): Passing null to parameter #3 ($subject) of type arra...

2025年11月11日 22:48 状态: processing

🚨 错误信息

Deprecated: preg_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated in /www/wwwroot/err.dmxapi.cn/index.php on line 10

🤖 AI解决方案

标题:preg_replace参数null弃用警告

原文:Passing null to parameter #3 ($subject) of type array|string is deprecated
译文:向第三个参数($subject)传递null值已弃用,该参数应为数组或字符串类型

原因分析

在PHP 8.1+版本中,preg_replace()函数的第三个参数$subject不再允许接受null值。您的代码在第10行向该参数传递了null,触发了弃用警告。

解决方案

方案1:检查是否为null并设置默认值

// 修复前
$result = preg_replace($pattern, $replacement, $subject);

// 修复后
$subject = $subject ?? '';
$result = preg_replace($pattern, $replacement, $subject);

方案2:使用三元运算符

$result = preg_replace($pattern, $replacement, $subject ?: '');

方案3:添加类型检查

if ($subject === null) {
    $subject = '';
}
$result = preg_replace($pattern, $replacement, $subject);

️ 预防措施

  • 参数验证:在使用字符串处理函数前,务必验证参数类型和值
  • PHP版本兼容:升级到PHP 8.1+时,检查所有可能传递null值的函数调用
  • 使用严格模式:开启严格类型检查可提前发现类型相关问题
// 推荐:添加参数验证函数
function safePregReplace($pattern, $replacement, $subject) {
    if ($subject === null) {
        $subject = '';
    }
    return preg_replace($pattern, $replacement, $subject);
}