首页 > 解决方案 > PHP 正则表达式:如何将 rel=stylesheet 替换为 rel=preload?

问题描述

我需要替换 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>

标签: phpcssregex

解决方案


也许正则表达式看起来是一个更简单的解决方案,但它可能隐藏了很多陷阱。在这种情况下,我将使用 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>

推荐阅读