为什么这个 preg_replace 调用返回 NULL? [英] Why does this preg_replace call return NULL?

查看:67
本文介绍了为什么这个 preg_replace 调用返回 NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does this call return NULL? Is the regex wrong? With the test input it doesn't return NULL. The docs say NULL indicates an error but what error could it be?

$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 )

推荐答案

您的正则表达式导致 灾难性的回溯并导致 PHP 正则表达式引擎失败.您可以使用 preg_last_error() 函数 检查这个.

Your regex is causing catastrophic backtracking and causing PHP regex engine to fail. You can use preg_last_error() function to check this.

$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 返回值.根据 preg_replace 的 PHP 文档:

You are getting NULL return value from preg_replace due to this error. As per PHP doc of preg_replace:

如果找到匹配项,将返回新的主题,否则主题将保持不变或如果发生错误则返回NULL.

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 修饰符时,点匹配任何字符,包括换行符.


Fix: You don't need (\s|.) when using s modifier (DOTALL). since dot matches any character including newline when using s modifier.

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

You should just use this regex:

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

这篇关于为什么这个 preg_replace 调用返回 NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆