php - Find <p> that contains image(s) and change style of that <p> -


i'm parsing wordpress post html through php. want images centered. alone easy enough, however, want images on same line centered together. in order need apply attribute class="image-content" <p> block.

how do php?

this post in editor:

enter image description here

and html wordpress provides post:

<p>single line paragraph.</p> <p>     <a href="image.png">         <img class="alignnone wp-image-39 size-thumbnail" src="image.png" width="150" height="150" />     </a> </p> <p>     multi line paragraph multi line paragraph      multi line paragraph multi line      paragraph multi line paragraph      multi line paragraph multi line paragraph      multi line paragraph multi line      paragraph multi line paragraph       multi line paragraph multi line paragraph       multi line paragraph multi line       paragraph multi line paragraph       multi line paragraph multi line paragraph. </p> <p>     <a href="image.png">         <img class="alignnone wp-image-39 size-thumbnail" src="image.png" width="150" height="150" />     </a>     <a href="image.png">         <img class="alignnone wp-image-39 size-thumbnail" src="image.png" width="300" height="300" />     </a> </p> <p>end of post.</p> 

you can domdocument, xpath , simple replacement.

    $parse = new \domdocument();     $parse->loadhtml($html);      $xpath = new \domxpath($parse);     $images = $xpath->query('//p//img');      $re = "/(.*)/";     $subst = "$1 image-content";      foreach ($images $image) {         $class = preg_replace($re, $subst, $image->getattribute('class'), 1);         $image->setattribute('class',$class);     }      $htmlfinal = $parse->savehtml(); 

edit

if want attach class containing p element, can use this:

    $parse = new \domdocument();     $parse->loadhtml($html);      $xpath = new \domxpath($parse);     $ps = $xpath->query('//p');      foreach ($ps $p) {         if ($p->getelementsbytagname('img')->length > 0) $p->setattribute('class', 'image-content');                }      $htmlfinal = $parse->savehtml(); 

if p tags may have class set before parsing dom, should combine 2 examples add new class instead of setting it.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -