preg match – PHP preg_match (.*) not matching past line breaks-ThrowExceptions

Exception or error:

I have this data in a LONGTEXT column (so the line breaks are retained):

Paragraph one
Paragraph two
Paragraph three
Paragraph four

I’m trying to match paragraph 1 through 3. I’m using this code:

preg_match('/Para(.*)three/', $row['file'], $m);

This returns nothing. If I try to work just within the first line of the paragraph, by matching:

preg_match('/Para(.*)one/', $row['file'], $m);

Then the code works and I get the proper string returned. What am I doing wrong here?

How to solve:

Use s modifier.

preg_match('/Para(.*)three/s', $row['file'], $m);

http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Answer:

Add the multi-line modifier.

Eg:

preg_match('/Para(.*)three/m', $row['file'], $m)

Answer:

Try setting the regex to dot-all (the extra ‘s’ parameter at the end), so it includes line breaks:

preg_match('/Para(.*)three/s', $row['file'], $m);

Answer:

If you don’t like / at the start and and, use T-Regx

$m = Pattern::of('Para(.*)three')->match($row['file'])->first();

Leave a Reply

Your email address will not be published. Required fields are marked *