1

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.

7
  • You don't have \r\ns do you? How about \R\h*\R+ Commented Feb 3, 2017 at 22:10
  • but the code works on the same text on the regex101 link. Commented Feb 3, 2017 at 22:11
  • @bobblebubble yes, \R works. cheers, stick it in an answer :) Commented Feb 3, 2017 at 22:12
  • (incidentally I was searching earlier for a special character for newline characters but didn't find \R ... I knew the cause of this problem was something silly..... ) Commented Feb 3, 2017 at 22:13
  • @dan08 that's just global so it doesn't stop after the first match, habit for working with repeating matches. doesn't apply as preg_replace does that automatically Commented Feb 3, 2017 at 22:15

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.