【问题标题】:Remove /Strip unwanted function (preg_replace)删除 /Strip 不需要的功能(preg_replace)
【发布时间】:2016-02-18 11:55:02
【问题描述】:

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

    // 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后端和输出中的函数get:

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

我们如何才能达到这一点?

【问题讨论】:

  • 有嵌套括号吗?否则你可以试试something like this
  • 塔安克斯!!!此时不是。但也许您可以针对这种情况提供解决方案?

标签: php regex replace preg-replace strip


【解决方案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 获得)

【讨论】:

  • 不客气!如果需要,可以选择分号;?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多