Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

PHP's preg_replace regex that matches multiple lines

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...