示例:
<?php
$content ='<a href="">REMOVE ME</a>
<a href="">KEEP ME</a>
<a href="">REMOVE PLEASE</a>
<a href="">KEEP remove</a>';
?>
我想删除所有带关键字remove的锚点。这可能在PHP?
答案 0 :(得分:2)
如果您需要删除文本中包含“删除”关键字的所有链接,则可以执行以下操作:
$content ='<a href="">REMOVE ME</a>
<a href="">KEEP ME</a>
<a href="">REMOVE PLEASE</a>
<a href="">KEEP remove</a>';
$dom = new DOMDocument;
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('a') as $node) {
if(stripos($node->textContent,'remove') === false)
echo $dom->saveHtml($node), PHP_EOL;
}
如果您需要删除href
中包含'remove'关键字的所有链接,请使用以下foreach
循环
$content ='<a href="google.com">REMOVE ME</a>
<a href="yahoo.com">KEEP ME</a>
<a href="gmail.com">REMOVE PLEASE</a>
<a href="test.com">KEEP remove</a>
<a href="remove.com">KEEPKEEP</a>';
$dom = new DOMDocument;
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('a') as $node) {
$node_href='';
if($node->hasAttribute( 'href' ))
$node_href = $node->getAttribute( 'href' );
if(stripos($node->textContent,'remove') === false && stripos($node_href,'remove') === false)
echo $dom->saveHtml($node), PHP_EOL;
}
答案 1 :(得分:1)
试试这个
$content = preg_replace(array('"<a href(.*?)>"', '"</a>"'), array('',''), $content);
答案 2 :(得分:1)
我还认为DOMDocument
是此类案例的最佳解决方案。但另一种方法是使用preg_replace
快速解决方案(仅适用于您的情况):
$cleared_content = preg_replace("/<a href=[\"\"|'']+>.*?remove.*?<\/a>/iu","",$content);