Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
418 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
Line 2
Line 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 (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
Line 2
Line 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
Line 2
Line 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
Line 2
Line 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...