我希望正则表达式从我的内容中删除所有外部链接,只保留提供的域的链接。
例如。
$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/