-->

Wrap Text in P tag

2019-03-27 00:47发布

问题:

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.

回答1:

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


回答2:

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

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


回答3:

$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.