I would like to use DOMDocument or another proposed method to do the following in wordpess:
I have this html saved in a variable:
<div id="gallery-3232" class="gallery gallery-3232">
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
</div>
And I would like to end up with a variable containing that:
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
How can I do this but without javascript. With the use of PHP.
Thabnk you
I just tested this, I think it's what you require. Basically load the HTML into a DOMDocument, get the element you need by ID and then iterate through its child nodes and output:
$html = '<div id="gallery-3232" class="gallery gallery-3232">
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
</div>
';
$doc = new DomDocument();
$doc->loadHtml($html);
$div = $doc->getElementById('gallery-3232');
$output = '';
foreach($div->childNodes as $element)
{
$output .= $element->ownerDocument->saveHtml($element);
}
echo $output;
$source = '<div id="gallery-3232" class="gallery gallery-3232">
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
</div>';
$list = new DOMDocument();
$list->loadHTML($source);
$listItems = $list->getElementsByTagName('li');
$listString = "";
foreach ($listItems as $list) {
$listString .= $list->C14N();
}
echo $listString;
Here's a quick and dirty way using a regex:
$string = preg_replace('~</?div[^>]*>~', '', $string);
Note: like I said, this is a quick and dirty way. If you're sure of your input - use this. However, if you are filtering uncertain input, you'd be better off parsing it properly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.