【问题标题】:PHP Regex: How to replace rel=stylesheet to rel=preload?PHP 正则表达式:如何将 rel=stylesheet 替换为 rel=preload?
【发布时间】:2019-05-24 14:09:50
【问题描述】:

我需要替换 rel 标签。原代码:

<link href="style.css" rel="stylesheet" />

必要代码:

<link href="style.css" rel="preload" as="style" onload="this.onload=null;this.rel='stylesheet'" />
<noscript><link href="style.css" rel="stylesheet" /></noscript>

【问题讨论】:

  • 你又是如何做到这一点的?

标签: php css regex


【解决方案1】:

也许正则表达式看起来是一个更简单的解决方案,但它可能隐藏了很多陷阱。在这种情况下,我会使用 DOM 进行必要的更改。

$html = '<link href="style.css" rel="stylesheet">';

libxml_use_internal_errors(true);
$dom = new DomDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);

foreach ($xpath->query('//link[@rel="stylesheet"]') as $link) {
    // Insert a copy of link inside the <noscript>
    $noscript = $dom->createElement('noscript');
    $noscript->appendChild($link->cloneNode(true));
    $link->parentNode->insertBefore($noscript, $link->nextSibling);

    // Modify the link attributes
    $link->setAttribute('rel', 'preload');
    $link->setAttribute('as', 'style');
    $link->setAttribute('onload', "this.onload=null;this.rel='stylesheet'");
}

echo $dom->saveHTML();

以上输出:

<link href="style.css" rel="preload" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link href="style.css" rel="stylesheet"></noscript>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 2020-04-20
    相关资源
    最近更新 更多