douzhang1115 2016-01-21 16:33
浏览 48
已采纳

RegEx查找所有锚标签,包括带图像的锚标签[重复]

I am trying to find all <a> tags and add a div around them. How do you change the RegEx to match <a><img></a> as well as <a>text</a>, or any tags within the <a> tag. I have:

<php

    $a_pattern = '@<a\s*.*>.*(<.*>)?.*</a>@i';
    $out = preg_replace_callback($a_pattern,"match_callback",$html);
    function match_callback($matches)
    {
         var_dump($matches);
    }

?>
</div>
  • 写回答

1条回答 默认 最新

  • dongwan0574 2016-01-21 22:54
    关注

    Here is how you can do it with a built-in PHP DOM parser (using with a some fake HTML, but you will get the idea):

    <?php
    $doc = new DOMDocument('1.0', 'UTF-8');
    $doc = DOMDocument::loadHTML('<body>
         <a href="somewere"><img src="www.foo.com/example.gif" class="foo" alt="..."><br></a>
         <a href="somewere again"><img src="www.bar.com/1.jpg" class="bar" alt="..."></a>
         <a href="somewere again and back">Text</a>
         </body>
    ', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    
    foreach ($doc->getElementsByTagName('a') as $a_node) {
       $div = $a_node->ownerDocument->createElement('div');
       $node = $a_node->parentNode->insertBefore($div, $a_node);
       $node->appendChild($a_node);
    }
    echo $doc->saveHTML();
    

    Output of the sample demo:

    <body>
    <div><a href="somewere"><img src="www.foo.com/example.gif" class="foo" alt="..."><br></a></div>
    <div><a href="somewere%20again"><img src="www.bar.com/1.jpg" class="bar" alt="..."></a></div>
    <div><a href="somewere%20again%20and%20back">Text</a></div>
    </body>
    

    You can also add attributes with the help of:

    $node->setAttribute('class', 'title');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗