【问题标题】:how to add attribute rel nofollow on tag a with regex如何使用正则表达式在标签a上添加属性rel nofollow
【发布时间】:2017-05-08 07:33:04
【问题描述】:

如何使用正则表达式在标签 a 上添加属性 rel nofollow

示例:

<a href="http://www.test.org/5521" rel="follow">test1</a>
<a href="http://www.test.org/5522" rel="external">test1</a>
<a href="http://www.test.org/5523">test1</a>

收件人:

<a href="http://www.test.org/5521" rel="nofollow">test1</a>
<a href="http://www.test.org/5522" rel="nofollow">test1</a>
<a href="http://www.test.org/5523" rel="nofollow">test1</a>

【问题讨论】:

    标签: php regex rel


    【解决方案1】:

    在这里使用 DOM 解析器会是一个更自然的解决方案:

    $html = <<<STR
    <html><body>
    <a href="http://www.test.org/5521" rel="follow">test1</a><br/>
    <a href="http://www.test.org/5522" rel="external">test1</a><br/>
    <a href="http://www.test.org/5523">test1</a>
    </body></html>
    STR;
    
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $links = $dom->getElementsByTagName("a");
    
    foreach($links as $link) { 
       $link->setAttribute('rel', 'nofollow');
    }
    
    echo $dom->saveHTML();
    

    PHP demo

    使用$links = $dom-&gt;getElementsByTagName("a");,您可以获得所有a 节点,使用$link-&gt;setAttribute('rel', 'nofollow');,您可以设置rel 属性,无论它是否存在。

    输出:

    <html><body>
    <a href="http://www.test.org/5521" rel="nofollow">test1</a><br>
    <a href="http://www.test.org/5522" rel="nofollow">test1</a><br>
    <a href="http://www.test.org/5523" rel="nofollow">test1</a>
    </body></html>
    

    【讨论】:

      【解决方案2】:

      Step1:从标签a中删除所有Rel

      $result = preg_replace('@rel="(.*)"@U', '', $html);
      

      第二步:在 taf a 上添加 Rel Nofollow

      $result = preg_replace('@<a(.*)>@U', '<a$1 rel="nofollow">', $result);
      

      【讨论】:

      • 为什么不使用 DOM?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多