将 target="_blank" 添加到所有 PDF 链接

Add target="_blank" to all PDF-links

我想向所有包含 href PDF 文件的链接添加 target="blank" 属性。为此,我想在 $content 上执行 preg_replace,包括所有 HTML,其中包含多个 PDf 链接。我认为这样的事情会起作用,但不幸的是它不起作用:

preg_replace('/((<a (?=.*\.pdf)(?!.*target="_blank").*?)>)/', ' target="_blank">', $content);

因此,例如应该发生以下情况:

$content = '<html>
<a href="http://www.example.com/file.pdf" title="File">
<a href="/file2.pdf" title="File2">
<a href="http://www.example.com/image.jpg" title="Image">
</html>';

preg_replace('/((<a (?=.*\.pdf)(?!.*target="_blank").*?)>)/', ' target="_blank">', $content);
    echo $content;

应该输出:

<html>
<a href="http://www.example.com/file.pdf" title="File" target="_blank">
<a href="/file2.pdf" title="File2" target="_blank">
<a href="http://www.example.com/image.jpg" title="Image">
</html>

你能帮我找到合适的 RegEx 吗?

如果有更简单的方法来完成同样的事情,我很想听听。

谢谢!

更好且不易出错的方法是使用 DOMDocumentDOMXPath。 要为 href 以 .pdf 结尾的所有锚点添加 target 属性,您可以这样做:

<?php
$content = '<html>
<a href="http://www.example.com/file.pdf" title="File">
<a href="/file2.pdf" title="File2">
<a href="http://www.example.com/image.jpg" title="Image">
</html>';

$doc = new DOMDocument();
$doc->loadHTML($content);
$xpath = new DOMXPath($doc);
/** @var DOMNodeList $anchors */
$anchors = $xpath->query('//a[substring(@href, string-length(@href) - 3) = ".pdf"][not(@target = "_blank")]');

/** @var DOMElement $anchor */
foreach($anchors as $anchor) {
    $anchor->setAttribute('target', '_blank');
}

echo $doc->saveHTML();