Wrap div around <p> tag using PHP (Wordpress) -


i using wordpress cms system, , want wrap every p tag in html need styling , positioning in website. found piece of code wonderfully me, overdoing right now.

this php code:

function tekst_wrapper($content) {     // match p tags     $pattern = '~<p.*</p>~';     preg_match_all($pattern, $content, $matches);      foreach ($matches[0] $match) {         // wrap matched p tag div         $wrappedframe = '<div>' . $match . '</div>';          //replace original p tag new in content        $content = preg_replace($pattern, $wrappedframe, $content);     }      return $content;     } add_filter('the_content', 'tekst_wrapper'); 

this adds div tags around each p tag. every p tag there in post, starts adding more div tags on each p tag. have 4 p tags, resulting html be:

<div>  <div>   <div>    <div>      <p>random text</p>    </div>   </div>  </div> </div> <div>  <div>   <div>    <div>      <p>random text</p>    </div>   </div>  </div> </div> <div>  <div>   <div>    <div>      <p>random text</p>    </div>   </div>  </div> </div> <div>  <div>   <div>    <div>      <p>random text</p>    </div>   </div>  </div> </div> 

obviously not need, since want each p tag wrapped in single div tag (or whatever replacement html going be). php skills aren't great, assume foreach causes add div tags every match finds in $matches array? there way fix this?

any appreciated.

you have several copies of same <p> tag in html , replacing every 1 of them on each iteration on foreach loop. use preg_replace or preg_replace_callback instead of foreaching.

function tekst_wrapper($content) {     // match p tags     $pattern = '~<p.*?</p>~';     return preg_replace_callback($pattern, function($matches) {         return '<div>' . $matches[0] . '</div>';     }, $content); } add_filter('the_content', 'tekst_wrapper'); 

note there question mark in pattern, make lazy.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -