php - 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>
解决方案
也许正则表达式看起来是一个更简单的解决方案,但它可能隐藏了很多陷阱。在这种情况下,我将使用 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>
推荐阅读
- javascript - 如何将 SqlDataReader 字符串转换为屏蔽密码字符串
- javascript - 将对象数组与对象进行比较并减少数量
- python - 切片列表的 enumerate() 无法按预期工作
- jquery - 如何使用 ipstack 和 ajax 获取用户的国家代码?
- java - 有没有办法加载(使用新文件())已导入项目文件夹的图像?
- r - 尝试在 S&P500 上计算 EWMA,但“[.xts`(x, i, which.i = TRUE) 中的错误:下标越界”中出现错误
- rust - 为什么 Clippy 建议传递 Arc 作为参考?
- google-play - 一些每日应用统计信息目前出现延迟。我们希望很快解决这个问题
- sql - Toad Notation - (Ix#) 是什么意思?
- excel - 如何将数组排序到范围