删除/删除不需要的功能(preg_replace)

时间:2016-02-18 11:55:03

标签: php regex replace preg-replace strip

例如,我们有一些这样的文字:

    // comments
    someFunc.f.log({
      obj:obj,
      other:other
    });
    console.log('here');
    someFunc.f.log({
      obj:obj,
      other:other
    }
);
    console.log('here');
    // comments

我想从这个文本中删除someFunc.f.log();函数在PHP后端和输出中得到:

// comments
console.log('here');
console.log('here');
// comments

我们如何达到这一点?

1 个答案:

答案 0 :(得分:1)

如果没有嵌套括号,您可以尝试使用this regex regex101

$str = preg_replace('/^\h*someFunc\.f\.log\([^)]*\);\R*|^\h+/m', "", $str);

like this demo at eval.in。如果有嵌套括号,请尝试使用that recursive regex regex101

'/^\h*someFunc\.f\.log(\((?>[^)(]*(?1)?)*\));\R*|^\h+/m'

like another demo at eval.in

  • ^匹配m多行flag
  • 行的开头
  • |是替换的管道符号
  • \h匹配水平空格
  • [^ ...打开一个否定的字符类
  • (?1)粘贴第一个带括号的subpattern
  • \R匹配任何换行序列

(regex101提供了更多解释和代码生成器)

相关问题