Someone has asked a similar question, but the accepted answer doesn’t meet my requirements.
Input:
<strong>bold <br /><br /> text</strong><br /><br /><br />
<a href="#">link</a><br /><br />
<pre>some code</pre>
I'm a single br, <br /> leave me alone.
Expected output:
<p><strong>bold <br /> text</strong><br /></p>
<p><a href="#">link</a><br /></p>
<pre>some code</pre>
<p>I'm a single br, <br /> leave me alone.</p>
The accepted answer I mentioned above will convert multiple br to p, and at last wrap all the input with another p. But in my case, you can’t wrap pre inside a p tag. Can anyone help?
update
the expected output before this edit was a little bit confusing. the whole point is:
-
convert multiple br to a single one (achieved with
preg_replace('/(<br />)+/', '<br />', $str);) -
check for inline elements and unwrapped text (there’s no parent element in this case, input is from $_POST) and wrap with <p>, leave block level elements alone.
Alright, I’v got myself an answer, and I believe this is gonna work really well.
It’s from WordPress…the
wpautopfunction.I’v tested it with the input (from my question), and the output is -almost- the same as I expected, I just need to modify it a bit to fit my needs.
Thanks dare2be, but I’m not very familiar with DOM manipulator in PHP.