0

I need some help with targeting a <div> with preg_replace() function.

HTML output of the_content():

<div class="content">

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

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

</div>

I'd like to add a class grid-col3 to the following <div>

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

Desired output:

<div class="content-html grid-col3 contentItem01" id="contentItem001">

The code:

$content = the_content();

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

Could you help me to adjust the above code so that it meets my needs? Many thanks!

1 Answers1

0

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();
Gillu13
  • 898
  • 6
  • 11