php - preg_match get div content with class -
i have code that
<div class="x-ic test"><div class="abc">test</div><table>.......</table><p>....</p><div style="margin:5px;"></div></div>
i tried few pattern didnt result want.
and need result below
<div class="abc">test</div><table>.......</table><p>....</p><div style="margin:5px;"></div>
use domdocument
- i've written code functions in case want perform similar operations again:
function dominnerhtml(domnode $element) { $innerhtml = ""; $children = $element->childnodes; foreach ($children $child) { $innerhtml .= $element->ownerdocument->savehtml($child); } return $innerhtml; } function getelcontentsbytagclass($html,$tag,$class) { $doc = new domdocument(); $doc->loadhtml($html);//turn $html string dom document $els = $doc->getelementsbytagname($tag); //find elements matching our tag name ("div" in example) foreach($els $el) { //for each element, class, , if matches return it's contents $classattr = $el->getattribute("class"); if(preg_match('#\b'.$class.'\b#',$classattr) > 0) return dominnerhtml($el); } } //calling it: $html = '<div class="x-ic test"><div class="abc">test</div><table>.......</table><p>....</p><div style="margin:5px;"></div></div>'; $ret = getelcontentsbytagclass($html,'div','x-ic test');//<div class="abc">test</div><table>.......</table><p>....</p><div style="margin:5px;"></div>
php fiddle - run (f9)
Comments
Post a Comment