doucheng1891 2018-10-26 20:48
浏览 294
已采纳

为什么这个preg_replace调用返回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 )
  • 写回答

1条回答 默认 最新

  • drk49438 2018-10-26 20:58
    关注

    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!';
    }
    

    Output:

    Backtrack limit was exhausted!
    

    You are getting NULL return value from preg_replace due to this error. As per 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.


    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密