Remove anchors from text

后端 未结 7 1618
醉酒成梦
醉酒成梦 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:29

    This question has been answered already but I thought I would add my solution to the mix. I like this better than the accepted solution because its a bit more to the point.

    $content = 
        preg_replace(array('"<a href(.*?)>"', '"</a>"'), array('',''), $content);
    
    0 讨论(0)
  • 2020-12-10 15:31

    Then you can try

    preg_replace('/<\/?a[^>]*>/','',$Source);
    

    I tried it online here on rubular

    0 讨论(0)
  • 2020-12-10 15:39

    You are looking for strip_tags().

    <?php
    
    // outputs 'google'
    echo strip_tags('<a href="http://www.google.com/" target="_blank">google</a>');
    
    0 讨论(0)
  • 2020-12-10 15:39

    using regex:

    preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$html);

    0 讨论(0)
  • 2020-12-10 15:47

    Have a try with:

    $str = '<p>paragraph</p><a href="http://www.google.com/" target="_blank" title="<>">google -> foo</a><div>In the div</div>';
    // first, extract anchor tag
    preg_match("~<a .*?</a>~", $str, $match);
    // then strip the HTML tags
    echo strip_tags($match[0]),"\n";
    

    output:

    google -> foo
    
    0 讨论(0)
  • 2020-12-10 15:49

    Exactly, it cannot be done properly using a regular expression.

    Here is an example using DOM :

    $xml = new DOMDocument(); 
    $xml->loadHTML($html); 
    
    $links = $xml->getElementsByTagName('a');
    
    //Loop through each <a> tags and replace them by their text content    
    for ($i = $links->length - 1; $i >= 0; $i--) {
        $linkNode = $links->item($i);
        $lnkText = $linkNode->textContent;
        $newTxtNode = $xml->createTextNode($lnkText);
        $linkNode->parentNode->replaceChild($newTxtNode, $linkNode);
    }
    

    It's important to loop backward whenever changes will be made to the DOM.

    0 讨论(0)
提交回复
热议问题