php - 为什么这个 preg_replace 调用返回 NULL?
问题描述
为什么这个调用返回 NULL?正则表达式错了吗?使用test
输入它不会返回 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 )
解决方案
您的正则表达式导致灾难性的回溯并导致 PHP 正则表达式引擎失败。您可以使用preg_last_error()
功能来检查这一点。
$r = preg_replace("/\[\](\s|.)*\]/s", "", $s);
if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
print 'Backtrack limit was exhausted!';
}
输出:
Backtrack limit was exhausted!
由于此错误,您将获得NULL
返回值。preg_replace
根据PHP 文档preg_replace
:
如果找到匹配项,则返回新的主题,否则主题将保持不变,如果发生错误则返回 NULL。
修复:(\s|.)
使用s
修饰符(DOTALL )时不需要。因为 dot 在使用s
修饰符时匹配任何字符,包括换行符。
你应该只使用这个正则表达式:
$r = preg_replace('/\[\].*?\]/s', "", $s);
echo preg_last_error();
//=> 0
推荐阅读
- python - 如何使用 Python 在 Firestore 中保存类型为“Reference”的文档
- jenkins - 两个类似的 Jenkins 项目给出了不同的结果
- python - 从 SARIMAX 模型打印结果时出现问题
- android - Android Studio build error logs not shown correctly
- sql - String masking with Regex at Oracle
- java - 如何在 JAX-RS 中自定义关系 OneToMany 的 JSON 输出
- c# - How to update naviation property with new values in EF Core?
- c# - 如何避免“XDocument.Parse(strHtml)”中的格式
- python - 当我在 tkinter 中使用条目时,我得到空字符串
- python - 如何将 XML 解析为 Django 模型?