【问题标题】:Remove links where href is disallowed删除不允许使用 href 的链接
【发布时间】:2012-04-30 05:36:48
【问题描述】:

我有一些这样的链接:

<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>

它应该通过链接递归地工作。

我发现这个删除所有链接的正则表达式:/&lt;\\/?a(\\s+.*?&gt;|&gt;)/,但我希望它保留 href 为 legallink.com 的链接。

这可以用正则表达式完成吗?还是应该使用 DOM 解析器?

【问题讨论】:

标签: php regex dom


【解决方案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();

【讨论】:

  • 我不是反对者,但我相信他想找到嵌套链接,而不是具有特定 href 的链接。他只是以href为例来说明应该保留哪个链接。
  • @JonathanKuhn - 我不应该因为不清楚的 OP 问题而被否决。除此之外,没有其他人发布替代答案。
  • 这就是我没有投反对票的原因。这个问题需要澄清一下。
  • @Elias:请查看更新后的代码,运行它并告诉我们您收到的错误消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
相关资源
最近更新 更多