php - 正则表达式删除除提供的域相关链接之外的外部链接 php

标签 php regex

我希望正则表达式从我的内容中删除所有外部链接,只保留提供的域的链接。

例如。

$inputContent = 'Lorem Ipsum <a href="http://www.example1.com" target="_blank">http://www.example1.com</a> lorem ipsum dummy text <a href="http://www.mywebsite.com" target="_blank">http://www.mywebsite.com</a>';

预期输出:

$outputContent = 'Lorem Ipsum lorem ipsum dummy text <a href="http://www.mywebsite.com" target="_blank">http://www.mywebsite.com</a>';

尝试过此解决方案,但不起作用。

$pattern = '#<a [^>]*\bhref=([\'"])http.?://((?<!mywebsite)[^\'"])+\1 *>.*?</a>#i';  
$filteredString = preg_replace($pattern, '', $content);

最佳答案

这里您真正需要的并不是正则表达式。您正在解析 HTML 文档,因此您应该为其选择正确的工具:DOMDocument .

<?php

$html = <<< HTML
Lorem Ipsum <a href="http://www.example1.com" target="_blank">http://www.example1.com</a>
lorem ipsum dummy text
<a href="http://mywebsite.com" target="_blank">http://www.mywebsite.com</a>
HTML;


$dom = new \DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED  | LIBXML_HTML_NODEFDTD);
$xpath = new \DOMXPath($dom);

$site = 'mywebsite.com';
// Query all `a` tags that don't start with your website domain name
$anchors = $xpath->query("//a[not(starts-with(@href,'http://{$site}')) and not(starts-with(@href,'http://www.{$site}'))]");

foreach ($anchors as $anchor) {
    $anchor->parentNode->removeChild($anchor);
}

echo $dom->saveHTML();

输出:

<p>Lorem Ipsum 
lorem ipsum dummy text
<a href="http://mywebsite.com" target="_blank">http://www.mywebsite.com</a></p>

关于php - 正则表达式删除除提供的域相关链接之外的外部链接 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39125424/

相关文章:

Java正则表达式搜索值

python - 正则表达式条件 : letters except 'crfl' at the end of the word or string are deleted?

java - 如何使用 PHP 或 Java 从 HTML 中提取 RDFa?

php - 自动完成先前值的字段

javascript - 使用 AJAX/JSON 返回整个文件

php - 如何在 PHP 上识别 Facebook 应用程序已卸载

php - 限制所选文件的数量

ruby - 寻找一个匹配所有单词的正则表达式,除了那些[括号内]

python - 如何使用 Python 和正则表达式将一组字母替换为符号

c# - .Net 多行正则表达式限制为整数