Q:

Replacing tags inside the parent tag using DOM PHP

Here is what I got:
<div id="list">
<ol>
  <li>Ordered list 1</li>
  <li>Ordered list 2</li>
  <ul><li>Unordered list inside ol ul</li></ul>
  <ol><li>Ordered list inside ol ol</li></ol>
</ol>

<ul>
  <li>Unordered list</li>
  <ol><li>Ordered list inside ul</li></ol>
</ul>

<ol>
  <li>Ordered list 1</li>
  <ol><li>Ordered list inside ol ol</li></ol>
</ol>
</div>

I need somehow replace LI tags only inside div id="list" -> OL tags
I need so that it replaces only LI tags only within the first OL tags and not UL or the once inside OL -> OL tags
I tried using preg_replace_callback but it only replaces all LI tags inside id="list" and from what i figured it will be over my head to limit replacement only with first ol tags and not the rest, so I been suggested to try out PHP DOM since it should be as easy as div id="list" -> OL
I would appreciate if someone got me started with the code, maybe with something as replacing all LI tags with in the first OL tag within the whole content.

A:

You shouldn't do this with regex. It's a very bad way to parse (HT|X)ML. Use a genuine parser instead.  Here's an example using PHP's DOMDocument class and the related DOMXPath:
<?php

$doc = new DomDocument(); 
$doc->loadXML('your HTML');
$xpath = new DOMXPath($doc);  

// get li elements in the first ol in the div whose id is list
$nodes = $xpath->query('//div[@id="list"]/ol[1]/li');

// change li elements to <li class='list'><div class='inline'>#####</div></li>
foreach ($nodes as $node) {
    $node->setAttribute('class', 'list');
    $number = $node->firstChild;
    $div = $doc->createElement('div');
    $div->setAttribute('class', 'inline');
    $div->appendChild($number);
    $node->appendChild($div);
}

// get the new HTML
$html = $doc->saveHTML();

NB also that you'll need to fix your ol and ul closing tags, which are currently unclosed.

