Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's preg_replace regex that matches multiple lines

Tags:

regex

php

How do I create a regex that takes into account that the subject consists of multiple lines?

The "m" modifier for one does not seem to work.

like image 553
Jeroen Beerstra Avatar asked Feb 10 '10 21:02

Jeroen Beerstra


1 Answers

Maxwell Troy Milton King is right, but since his answer is a bit short, I'll post this as well and provide some examples to illustrate.

First, the . meta character by default does NOT match line breaks. This is true for many regex implementations, including PHP's flavour. That said, take the text:

$text = "Line 1\nLine 2\nLine 3";

and the regex

'/.*/'

then the regex will only match Line 1. See for yourself:

preg_match('/.*/', $text, $match);
echo $match[0]; // echos: 'Line 1'

since the .* "stops matching" at the \n (new line char). If you want to let it match line breaks as well, append the s-modifier (aka DOT-ALL modifier) at the end of your regex:

preg_match('/.*/s', $text, $match);
echo $match[0]; // echos: 'Line 1\nLine 2\nLine 3'

Now about the m-modifier (multi-line): that will let the ^ match not only the start of the input string, but also the start of each line. The same with $: it will let the $ match not only the end of the input string, but also the end of each line.

An example:

$text = "Line 1\nLine 2\nLine 3";
preg_match_all('/[0-9]$/', $text, $matches);
print_r($matches); 

which will match only the 3 (at the end of the input). But:

but enabling the m-modifier:

$text = "Line 1\nLine 2\nLine 3";
preg_match_all('/[0-9]$/m', $text, $matches);
print_r($matches);

all (single) digits at the end of each line ('1', '2' and '3') are matched.

like image 51
Bart Kiers Avatar answered Sep 24 '22 23:09

Bart Kiers