Wrap set of P tags in div using preg_replace() method

  html, php, regex

I have some content in following pattern.

<h4>Some title text</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi, officia.</p>
<p>Lorem ipsum dolor sit amet consectetur.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>

<h4>Some title text</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi, officia.</p>
<p>Lorem ipsum dolor sit amet consectetur.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>

What I want to do is in PHP use preg_replace() and wrap all the P tags in a div tag as show below.

<h4>Some title text</h4>
<div>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi, officia.</p>
    <p>Lorem ipsum dolor sit amet consectetur.</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>
</div>


<h4>Some title text</h4>
<div>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi, officia.</p>
    <p>Lorem ipsum dolor sit amet consectetur.</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>
</div>

I am not very good with regular expressions so decided to post it here.

Source: Ask PHP

LEAVE A COMMENT