Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for use with php's preg_match to find a newline

I'm fairly new/rusty with regular expressions. I'm collecting a block of text from a textarea element and I want to check to see if the person who filled it used any paragraphs, amongst other things.

I'm using the following and I know it's wrong.

preg_match('/\r\n|\n|\r/', $_GET['text']);
like image 337
Ed Fearon Avatar asked Jun 01 '11 19:06

Ed Fearon


1 Answers

Your regex is not wrong. But for detecting paragraphs you will want to look for two consecutive newlines:

 preg_match('/(\r?\n){2}/'

The carriage return \r is optional, and I would just check for \n newline as most platforms treat that as linebreak. Obviously this check will fail if the submitted text is just a single line without paragraphs or newlines.

Alternatively you could also probe for two newlines with any sort of whitespace in between:

 preg_match('/(\s*\n){2}/'
like image 54
mario Avatar answered Sep 22 '22 04:09

mario