Reputation: 22770
This seems a really simple exercise but It's just not working out for me.
I have a text document, and felt an easy way to HTMLify it is to use a quick regex to translate 2 newlines into a </p><p>
, this is simple enough for what I need.
So; my regex:
\n\h*\n+
/** This matches the newline,
then any number (zero or more) whitespace
and then a second new line. **/
This works in regex101.com where I usually trial out my regexes. But in my PHP it's not working;
$text = trim($_POST['text']);
$text = strip_tags($_POST['text']);
/*** Find new Paragraphs ***/
$text = preg_replace("/\n\h*\n/","</p>\n<p>",$text);
$text = "<p>".$text."</p>";
My input:
30th Sep 16
Day 176 has seen more golf balls struck with growing frustration as I try
to train the brain, a short swim, and a dawning realisation which has led
to probably the biggest question that I have ever posed.
But my output on PHP is:
<p>30th Sep 16
Day 176 has seen more golf balls struck with growing frustration as I try
to train the brain, a short swim, and a dawning realisation which has led
to probably the biggest question that I have ever posed.</p>
Adding a $count
var to the preg_replace
returns zero, the match is not being found.
Expected output:
<p>30th Sep 16 </p>
<p>Day 176 has seen more golf balls struck with growing frustration as I try
to train the brain, a short swim, and a dawning realisation which has led
to probably the biggest question that I have ever posed.</p>
What am I missing? I'm sure it's simple but I can't see why it works on a site but not on my extremely simple script :-/
I have also tried substituting \n
for PHP_EOL
and various other permutations of the code, to no success.
Upvotes: 1
Views: 82
Reputation: 18565
Could be that you have \r\n
line breaks. Try escape sequence \R
for any linebreak sequence.
\R\h*\R+
See demo at regex101 or PHP Demo at eval.in
Upvotes: 1