【问题标题】:Regex replace h1 tag with h2 tag globally with php正则表达式用php全局用h2标签替换h1标签
【发布时间】:2017-12-08 13:17:13
【问题描述】:

我很难在一段内容中尝试用<h2> 替换<h1> 标记。

我得到的最接近的是:

preg_replace('/<h1[\s*](class|id|style)="(.*?)">(\w*?)<\/h1>/mi', '<h2 $1="$2">$3</h2>',  $content);

这里的问题是常规的 h1 行:

&lt;h1&gt;This is the heading&lt;/h1&gt;

不会被捕获。

这一行:

&lt;h1 style="font-size:13px"&gt;Another heading&lt;/h1&gt;

也不会被捕获,这让我感到困惑,因为它使用与 class 和 id 相同的设置,仅使用特殊字符,例如 -: 等。我以为.*? 会覆盖。

任何帮助将不胜感激。

【问题讨论】:

    标签: php regex preg-replace regex-group


    【解决方案1】:

    这里有类似的东西,包含所有属性:(除了 > 属性之外的所有东西)

    $str= <<<EOT
    <h1>This is the heading</h1>
    <h1 style="font-size:13px">Another heading</h1>
    EOT;
    
    $str = preg_replace('#<h1([^>]*)>(.*)</h1>#m','<h2$1>$2</h2>', $str);
    print $str;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-28
      • 2013-06-02
      • 1970-01-01
      • 2012-07-06
      • 2011-11-20
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多