troubleshooting Question

Replace newlines with HTML paragraph tags

Avatar of evco
evcoFlag for United States of America asked on
PHPRegular Expressions
13 Comments1 Solution938 ViewsLast Modified:
The following replaces 2 or more newlines with paragraph tags however if a paragraph (2 or more newlines) contains a single newline it is not wrapped in paragraph tags.

I have a basic understanding of regular expressions but I'm at a loss on how to fix the regex below to correct problem.

I've figured out that it DOES work when newlines are \r but not when they are \r\n or \n.

The example below will output:
<p>This is the first paragraph.</p>
This is the second
paragraph.

But I need it to output::
<p>This is the first paragraph.</p>
<p>This is the second
paragraph.</p>
$string = "This is the first paragraph.\n\nThis is the second\nparagraph.";
echo preg_replace("{(?:^|(?:\x0d\x0a){2,}|\x0a{2,}¦\x0d{2,})(.+?)(?=(?:(\x0d\x0a){2,}|\x0d{2,}|\x0a{2,}|$))}", "</p>$1<p>", $string)
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 13 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 13 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros