【问题标题】:Adding class to a <div> in the_content() [duplicate]在 the_content() 中将类添加到 <div> [重复]
【发布时间】:2020-07-16 14:51:59
【问题描述】:

在使用 preg_replace() 函数定位 &lt;div&gt; 时,我需要一些帮助。

the_content() 的 HTML 输出:

<div class="content">

<link rel="import" href="..." data-target="self">

 <div class="content-html contentItem01" id="contentItem001">
  <article>
  ... 
  </article>
 </div>

</div>

我想给下面的&lt;div&gt;添加一个类grid-col3

&lt;div class="content-html contentItem01" id="contentItem001"&gt;

期望的输出:

&lt;div class="content-html grid-col3 contentItem01" id="contentItem001"&gt;

代码:

$content = the_content();

$content = preg_replace(
  '#^(\s*<[^>]+?content-html)#',
  '$1 grid-col3',
  $content
);

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

【问题讨论】:

  • 为什么你的正则表达式中有^(主题开始anchor)?只需删除它,您的代码就会按预期匹配和替换。
  • 您使用的是默认内容还是任何元素?
  • 不鼓励尝试使用正则表达式解析 HTML。我建议调查 DOMDocument

标签: php regex wordpress


【解决方案1】:

正如 cmets 中所述,正则表达式在这里不是最佳选择,应首选 DOMDocument 类,如下例所示。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-01
    • 2013-06-05
    • 1970-01-01
    • 2012-01-22
    • 2015-11-20
    • 2020-10-23
    • 2020-01-08
    • 2014-12-04
    相关资源
    最近更新 更多