【问题标题】:PHP regEx help needed with /*<##> </##>*//*<##> </##>*/ 需要 PHP regEx 帮助
【发布时间】:2014-10-31 12:40:40
【问题描述】:

我正在努力使用正则表达式,但无法使其正常工作。 我已经尝试过: SO questiononline tool

$text = preg_replace("%/\*<##>(?:(?!\*/).)</##>*\*/%s", "new", $text);

但是没有任何效果。 我的输入字符串是:

$input = "something /*<##>old or something else</##>*/ something other";

预期结果是:

something /*<##>new</##>*/ something other

【问题讨论】:

  • 您没有前瞻掩码 (.) 匹配所有的量词。因此,它只接受您的 cmets 中的一个字符的字符串。同样,仅替换为 new 不会重新实例化 /*&lt;##&gt; 评论标记。

标签: php regex


【解决方案1】:

我看到这里指出了两个问题,您没有捕获组来替换替换调用中的定界标记,并且您的 Negative Lookahead 语法缺少 repetition operator

$text = preg_replace('%(/\*<##>)(?:(?!\*/).)*(</##>*\*/)%s', '$1new$2', $text);

不过,由于您使用的是 s(dotall)修饰符,因此您可以将前瞻替换为 .*?

$text = preg_replace('%(/\*<##>).*?(</##>*\*/)%s', '$1new$2', $text);

或者考虑在不捕获组的情况下使用环视组合来执行此操作。

$text = preg_replace('%/\*<##>\K.*?(?=</##>\*/)%s', 'new', $text);

【讨论】:

    【解决方案2】:

    测试:

    $input = "something /*<##>old or something else</##>*/ something other";
    
    echo preg_replace('%(/\*<##>)(.*)(</##>\*/)%', '$1new$3', $input);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 2015-09-24
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2018-02-23
      相关资源
      最近更新 更多