首页 > 解决方案 > 将类添加到

在 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
);

你能帮我调整上面的代码以满足我的需要吗?非常感谢!

标签: phpregexwordpress

解决方案


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

推荐阅读