Reputation: 49
in the text, i would like to replace the div tag li. But not everyone just certain well defined. In this case, those that have id that begins "tab-*" I need something using PHP functions easily from text:
<div id="tab-141285" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</div>
<div id="tab-85429" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</div>
get this text
<li id="tab-141285" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</li>
<li id="tab-85429" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</li>
Can you advise me?
Thank you
Upvotes: 0
Views: 90
Reputation: 26385
Regular expressions are not adequate for parsing HTML. Any regex you try to use will be fragile. I suggest using the DOM extension for this instead.
The idea is to:
<div>
elements that have an id
attribute that begins with "tab-"
using the XPath query //div[starts-with(@id, "tab-")]
<li>
element for each of them.<div>
's attributes and child nodes to the new <li>
element.<div>
with the new <li>
.Because your string doesn't have a root element, we'll do a little dance before and after to put it in one then rebuild it.
$html = <<<'HTML'
<div id="tab-141285" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</div>
<div id="tab-85429" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</div>
HTML;
$dom = new DOMDocument();
$dom->loadHTML("<div>$html</div>", LIBXML_HTML_NOIMPLIED);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//div[starts-with(@id, "tab-")]');
foreach ($nodes as $node) {
$li = $dom->createElement('li');
while ($node->attributes->length) {
$li->setAttributeNode($node->attributes->item(0));
}
while ($node->firstChild) {
$li->appendChild($node->firstChild);
}
$node->parentNode->replaceChild($li, $node);
}
$html = '';
foreach ($dom->documentElement->childNodes as $node) {
$html .= $dom->saveHTML($node);
}
echo $html;
<li id="tab-141285" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</li>
<li id="tab-85429" class="my-class">
<div class="my-subclass">
<div>
Lorem ipsum dolor sit amet consectetuer
</div>
</div>
</li>
Upvotes: 1
Reputation: 4321
use domdocument xml component of php just load the string in domdocument object and search for element then get its attribute and check its id and compare using preg_replace and remove if it met your condition
Upvotes: 0