Remove anchors from text

后端 未结 7 1619
醉酒成梦
醉酒成梦 2020-12-10 15:01

I need to remove anchor tags from some text, and can\'t seem to be able to do it using regex.
Just the anchor tags, not their content.
For instance,

相关标签:
7条回答
  • 2020-12-10 15:50

    Much of the regex here did not help me. Some of it removes the content inside the anchor (which is not at all what OP asked for) and not all of the content at that, some of it will match any tag beginning with a, etc.

    This is what I created for my needs at work. We had an issue where passing HTML to wkhtmltopdf that had anchor tags (with many data attributes and other attributes) would sometimes prevent the PDF from producing, so I wanted to remove those while keeping the text.

    Regex:

    /</?a( [^>]*)?>/ig

    In PHP you can do:

    $text = "<a href='http://www.google.com/'>Google1</a><br>" .
            "<a>Google2</a><br>" .
            "<afaketag href='http://www.google.com'>Google2</afaketag><br>" .
            "<afaketag>Google4</afaketag><br>" . 
            "<a href='http://www.google.com'><img src='someimage.jpg'></a>";
    echo preg_replace("/<\/?a( [^>]*)?>/i", "", $text);
    

    Outputs:

    Google1<br>Google2<br><afaketag href='http://www.google.com'>Google2</afaketag><br><afaketag>Google4</afaketag><br><img src='someimage.jpg'>
    
    0 讨论(0)
提交回复
热议问题