Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

php - Remove anchors from text

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, <a href="http://www.google.com/" target="_blank">google</a> would become google.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...