php - 将类添加到在 the_content()
问题描述
我需要一些帮助来定位<div>
withpreg_replace()
函数。
的 HTML 输出the_content()
:
<div class="content">
<link rel="import" href="..." data-target="self">
<div class="content-html contentItem01" id="contentItem001">
<article>
...
</article>
</div>
</div>
我想grid-col3
在以下内容中添加一个类<div>
<div class="content-html contentItem01" id="contentItem001">
期望的输出:
<div class="content-html grid-col3 contentItem01" id="contentItem001">
编码:
$content = the_content();
$content = preg_replace(
'#^(\s*<[^>]+?content-html)#',
'$1 grid-col3',
$content
);
你能帮我调整上面的代码以满足我的需要吗?非常感谢!
解决方案
As mentioned in the comments, regex are not the best option here and the DOMDocument
class shall be preferred, as in the following example.
$dom = new DOMDocument();
// the following line will probably raise a warning in the case of the example
// provided in the question because the "article" tag is considered not valid.
$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach($dom->getElementsByTagName('div') as $div){
$oldClass = $div->getAttribute('class');
$newClass = str_replace('content-html', 'content-html grid-col3', $oldClass);
$div->setAttribute('class', $newClass);
}
$content = $dom->saveHtml();
推荐阅读
- ios - Satellite 不会向仅适用于 ios 的 Adobe Analytics 中的报表套件发送请求
- java - 使用 maven 项目与 lotus notes 数据库连接的问题
- css - 如何在 VueJS 项目中设置 SASS(vue-cli,无 webpack 配置)
- nginx - Nginx.ingress.kubernetes.io/proxy-body-size 不工作
- php - 有没有办法从 Wordpress 访问单独的本地数据库?
- synchronization - 是否有一些用于同步本地服务器和 Azure VM 的解决方案
- android - 将文本视图与约束布局对齐
- azure - 是否可以使用转换 DNS 后缀的 Bind9 设置 DNS 转发?
- c# - 如何利用用户在 DataContext 列表中添加的信息?
- android - 别名资源文件中当前显示的布局的名称