Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match until double line break

Tags:

php

preg-match

I have this data in a mysql field:

First text text text text
 text text text text
 text text text text text text
 text text text text text text

Second text text text text
 text text text text
 text text text text text text
 text text text text text text

I'm trying to preg match from the first word until the double line break. I've tried:

preg_match('/First(.*)\n\n/', $mysqlrow, $m);

This returns no rows. I've also tried the m and s modifiers, which don't return the proper string. I've also tried \r\n which doesn't return anything.

How do you do this

like image 788
Norse Avatar asked Mar 17 '26 09:03

Norse


2 Answers

You need the s modifier and you also need to change your wildcard quantifier to be non-greedy:

preg_match('/First(.*?)\n\n/s', $mysqlrow, $m);

The s option will cause the . wildcard to match \n and the non-greedy will cause the * wildcard to not eat up all the \n\n it runs across before matching \n\n.

You can also optionally match the \r just in case you have that in your database:

preg_match('/First(.*?)\r?\n\r?\n/s', $mysqlrow, $m);
like image 160
jimp Avatar answered Mar 18 '26 23:03

jimp


It's the other flag you need. Flag "s" allow the dot to capture line break. But it will then be eating your double '\n'.

You can try :

preg_match('/First(.*?)\n\n/s', $mysqlrow, $m);

with the ? inverting the greedy behaviour. Note that spliting a string can be done with the split function which might be more suitable for your case.

like image 31
Valentin Perrelle Avatar answered Mar 18 '26 21:03

Valentin Perrelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!