PHP的preg_replace正则表达式,可匹配多行 [英] PHP's preg_replace regex that matches multiple lines

查看:173
本文介绍了PHP的preg_replace正则表达式,可匹配多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建考虑到主题由多行组成的正则表达式?

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

其中一个的"m"修饰符似乎不起作用.

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

推荐答案

麦克斯韦·特洛伊·米尔顿·金(Maxwell Troy Milton King)是对的,但是由于他的回答有点短,我也将其发布并提供一些示例来说明.

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.

首先,默认情况下.元字符与换行符不匹配.这对许多正则表达式实现都是正确的,包括PHP的风格.也就是说,请输入文字:

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";

和正则表达式

'/.*/'

则正则表达式将仅匹配Line 1.亲自看看:

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

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

,因为.*\n处停止匹配"(换行符).如果您也想让它与换行符匹配,请在正则表达式的末尾附加s-修饰符(即DOT-ALL修饰符):

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'

现在介绍m-修饰符(多行):这将使^不仅匹配输入字符串的开头,而且匹配每行的开头.与$相同:它将使$不仅匹配输入字符串的末尾,而且匹配每行的末尾.

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.

一个例子:

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

,它将仅匹配3(在输入的末尾).但是:

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

但启用m-修饰符:

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

每行末尾的所有(单个)数字("1","2"和"3")都匹配.

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

这篇关于PHP的preg_replace正则表达式,可匹配多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆