Php 删除不允许href的链接
我有一些这样的链接:Php 删除不允许href的链接,php,regex,dom,Php,Regex,Dom,我有一些这样的链接: <a href="http://illegallink.com"><img src="something.jpg" /><a href="http://legallink.com">legal</a></a> 我想删除所有不包含“legallink.com”的链接。但是仍然保留内容。因此,上述输入将输出: <img src="something.jpg" /><a href="http://
<a href="http://illegallink.com"><img src="something.jpg" /><a href="http://legallink.com">legal</a></a>
我想删除所有不包含“legallink.com”的链接。但是仍然保留内容。因此,上述输入将输出:
<img src="something.jpg" /><a href="http://legallink.com">legal</a>
它应该通过链接递归地工作
我发现这个正则表达式删除了所有链接:/|>)/
,但我希望它保留href为legallink.com的链接
这可以用正则表达式完成吗?还是应该使用DOM解析器?错误报告(~0);显示错误(1);
error_reporting(~0); display_errors(1);
$code = '<a href="http://illegallink.com"><img src="something.jpg" /><a href="http://legallink.com">legal</a></a>';
$document = new DOMDocument();
$document->loadHTML($code);
$parser = new DOMXPath($document);
foreach($parser->query("//a") as $node)
{
if (!preg_match("/^http:\/\/legallink.com/i", $node->getAttribute("href")))
{
$node->parentNode->replaceChild($node->nodeValue, $node);
}
}
echo $document->saveXML();
$code='';
$document=新的DOMDocument();
$document->loadHTML($code);
$parser=newdomxpath($document);
foreach($parser->query(//a)作为$node)
{
如果(!preg_match(“/^http:\/\/legallink.com/i”,$node->getAttribute(“href”))
{
$node->parentNode->replaceChild($node->nodeValue,$node);
}
}
echo$document->saveXML();
需要一个DOM解析器,特别是对于您的示例中的嵌套标记。有人能举个例子说明如何实现我想要的吗?我看了很多,但找不到解决方案。可能在这里:?这个相关的问题可能很有用:我不是downvoter,但我相信他想找到嵌套链接,而不是带有特定href的链接。他只是以href为例来说明应该保留哪个链接。@JonathanKuhn-我不应该因为这个问题而被否决。除此之外,没有其他人给出替代答案。这就是我没有投反对票的原因。这个问题需要澄清。@Elias:请查看更新的代码,运行它,并告诉我们您收到的错误消息。