The Pixel Developer
The Pixel Developer

Reputation: 13430

Wrap Text in P tag

I'm trying to figure out how to wrap text like this:

Morbi nisl tortor, consectetur vitae laoreet eu, lobortis id ipsum. Integer scelerisque blandit pulvinar. Nam tempus mi eget nunc laoreet venenatis. Proin viverra, erat at accumsan tincidunt, ante mi cursus elit, non

congue mauris dolor ac elit. Maecenas mollis nisl a sem semper ornare. Integer nunc purus, dapibus nec dignissim sed, dictum eget leo. Etiam in mi ut erat pretium fringilla sed

Into this:

<p>Morbi nisl tortor, consectetur vitae laoreet eu, lobortis id ipsum. Integer scelerisque blandit pulvinar. Nam tempus mi eget nunc laoreet venenatis. Proin viverra, erat at accumsan tincidunt, ante mi cursus elit, non</p>

<p>congue mauris dolor ac elit. Maecenas mollis nisl a sem semper ornare. Integer nunc purus, dapibus nec dignissim sed, dictum eget leo. Etiam in mi ut erat pretium fringilla sed</p>

Note the p tags around the text.

Upvotes: 9

Views: 11020

Answers (3)

Peter Bailey
Peter Bailey

Reputation: 105878

This should do it

$text = <<<TEXT
Morbi nisl tortor, consectetur vitae laoreet eu, lobortis id ipsum. Integer scelerisque blandit pulvinar. Nam tempus mi eget nunc laoreet venenatis. Proin viverra, erat at accumsan tincidunt, ante mi cursus elit, non

congue mauris dolor ac elit. Maecenas mollis nisl a sem semper ornare. Integer nunc purus, dapibus nec dignissim sed, dictum eget leo. Etiam in mi ut erat pretium fringilla sed
TEXT;

$paragraphedText = "<p>" . implode( "</p>\n\n<p>", preg_split( '/\n(?:\s*\n)+/', $text ) ) . "</p>";

Upvotes: 10

Matthew Vines
Matthew Vines

Reputation: 27561

$str = '<p>'. str_replace('\n\n', '</p><p>', $str) .'</p>';

OR

$str = '<p>'. preg_replace('\n{2,}', '</p><p>', $str) .'</p>';

To catch 2 or more.

Upvotes: 4

Jeremy Smyth
Jeremy Smyth

Reputation: 23493

Use preg_replace within a loop over all lines in your input:

$replacement = preg_replace("/(.*)/", "<p>$1</p>", $current_line);

Upvotes: 3

Related Questions