【问题标题】:Add target="_blank" to all PDF-links将 target="_blank" 添加到所有 PDF 链接
【发布时间】:2016-05-31 16:47:26
【问题描述】:

我想将target="blank"-属性添加到包含href 的PDF 文件的所有链接。为了做到这一点,我想在$content 上做一个preg_replace,包括所有带有多个 PDf 链接的 HTML。我认为这样的事情会起作用,但不幸的是它没有:

preg_replace('/((<a (?=.*\.pdf)(?!.*target="_blank").*?)>)/', '$2 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").*?)>)/', '$2 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>

你能帮我找到合适的正则表达式吗?

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

谢谢!

【问题讨论】:

  • 当您提出问题时,请添加输入和预期输出与实际输出的示例。这样可以更轻松地为您提供帮助!

标签: php regex replace preg-replace


【解决方案1】:

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

<?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();

【讨论】:

  • 像魅力一样工作,非常感谢!我还不知道DOMDocument()-class。
猜你喜欢
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
相关资源
最近更新 更多