drzbc6003 2018-10-10 15:24
浏览 131
已采纳

PHP preg_replace:将文本中的所有锚标记替换为带有正则表达式的href值

I want to replace all anchor tags within a text with their href value, but my pattern does not work right.

$str = 'This is a text with multiple anchor tags. This is the first one: <a href="https://www.link1.com/" title="Link 1">Link 1</a> and this one the second: <a href="https://www.link2.com/" title="Link 2">Link 2</a> after that a lot of other text. And here the 3rd one: <a href="https://www.link3.com/" title="Link 3">Link 3</a> Some other text.';
$test = preg_replace("/<a\s.+href=['|\"]([^\"\']*)['|\"].*>[^<]*<\/a>/i",'\1', $str);
echo $test;

At the end the text should look like this:

This is a text with multiple anchor tags. This is the first one: https://www.link1.com/ and this one the second: https://www.link2.com/ after that a lot of other text. And here the 3rd one: https://www.link3.com/ Some other text.

Thank you very much!

  • 写回答

3条回答 默认 最新

  • dqw7121 2018-10-10 16:25
    关注

    Just don't.

    Use a parser instead.

    $dom = new DOMDocument();
    // since you have a fragment, wrap it in a <body>
    $dom->loadHTML("<body>".$str."</body>");
    $links = $dom->getElementsByTagName("a");
    while($link = $links[0]) {
        $link->parentNode->insertBefore(new DOMText($link->getAttribute("href")),$link);
        $link->parentNode->removeChild($link);
    }
    $result = $dom->saveHTML($dom->getElementsByTagName("body")[0]);
    // remove <body>..</body> wrapper
    $output = substr($result, strlen("<body>"), -strlen("</body>"));
    

    Demo on 3v4l

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?