Benjir Ahmed Benjir Ahmed - 1 year ago 46
PHP Question

Regex to find text that are not surround by p tag in a article and give the text surround p tag.How to do it?

I have a article which has content on it . I want to find the unwrapped text(which are not surround by any tags) and then surround it by p tag.
code are given below-



<p>line 1 </p>
line 2 unwrapped
<p> line 3 </p>
line 4 unwrapped
<p> line 5 </p>
line 6 unwrapped





But i want the output like this-



<p>line 1 </p>
<p>line 2 unwrapped</p>
<p> line 3 </p>
<p>line 4 unwrapped</p>
<p> line 5 </p>
<p>line 6 unwrapped</p>




Thanks in advance

Answer Source

You shouldn't parse HTML with regex.
But in case you absolutely want to, here is one.

The following regex will select lines that doesn't use tags as stated:

^(?!<p>).*(?!<\/p>)

You can the replace the match with:

<p>$0</p>

See the regex demo

Here is an example:

$re = '/^(?!<p>).*(?!<\/p>)/m';
$str = '<p>line 1 </p>
line 2 unwrapped
<p> line 3 </p>
line 4 unwrapped
<p> line 5 </p>
line 6 unwrapped';
$subst = '<p>$0</p>';

$result = preg_replace($re, $subst, $str);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download