9
votes

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.

3
You're a Kohana guy! Check out text::auto_p() :)alex

3 Answers

10
votes

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>";
3
votes

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

$replacement = preg_replace("/(.*)/", "<p>$1</p>", $current_line);
3
votes
$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.