为什么这个 preg_replace 调用 return NULL?

Why does this preg_replace call return NULL?

为什么调用 return NULL? 正则表达式错误吗?对于 test 输入,它不会 return NULL。 文档说 NULL 表示错误,但它可能是什么错误?

$s = hex2bin('5b5d202073205b0d0a0d0a0d0a0d0a20202020202020203a');
// $s = 'test';
$s = preg_replace('/\[\](\s|.)*\]/s', '', $s);
var_dump($s);

// PHP 7.2.10-1+0~20181001133118.7+stretch~1.gbpb6e829 (cli) (built: Oct  1 2018 13:31:18) ( NTS )

您的正则表达式导致 catastrophic backtracking and causing PHP regex engine to fail. You can use preg_last_error() function 对此进行检查。

$r = preg_replace("/\[\](\s|.)*\]/s", "", $s);
if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
    print 'Backtrack limit was exhausted!';
}

输出:

Backtrack limit was exhausted!

由于此错误,您正在从 preg_replace 中获取 NULL return 值。根据 PHP doc of preg_replace:

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.


修复: 使用 s 修饰符 (DOTALL) 时不需要 (\s|.)。因为在使用 s 修饰符时点匹配任何字符,包括换行符。

你应该只使用这个正则表达式:

$r = preg_replace('/\[\].*?\]/s', "", $s);
echo preg_last_error();
//=> 0