简体   繁体   English

PHP和正则表达式:如何在多行上进行preg_match?

[英]PHP and regex: how to preg_match on multiple line?

My HTML is: 我的HTML是:

line1
line2

line3 59800 line4
line5
line6

My goal is to capture: (25 left characters)59800(25 right characters): 我的目标是捕获:(25个左字符)59800(25个右字符):

I tried with 我尝试过

/.{1,25}59800.{1,25}/igm

But I only captures: 但是我只捕获:

line3 59800 line4

How do I capture multiple lines? 如何捕获多行?

Here is the test: http://regexr.com/39498 这是测试: http : //regexr.com/39498

Instead of m , use the s (DOTALL) flag in your regex: 在正则表达式中使用s (DOTALL)标志代替m

/.{1,25}59800.{1,25}/s

The s modifier is used to make DOT match newlines as well where m is used to make anchors ^ and $ match in each line of multiline input. s修饰符用于使DOT匹配换行符,其中m用于使多行输入的每一行中的锚点^ and $匹配。

Adding to @anubhava's answer , which is correct: 添加到@anubhava的答案中 ,这是正确的:

  • You don't need the i flag as there are no letters mentioned in the regex 您不需要i标志,因为正则表达式中没有提到字母
  • The g flag doesn't exist in PHP. g标志在PHP中不存在。
  • You can also use (?s) to activate DOTALL mode, allowing the dot to match across lines 您还可以使用(?s)激活DOTALL模式,以允许点跨线匹配

In PHP you can do this: 在PHP中,您可以执行以下操作:

$regex = '~(?s).{1,25}59800.{1,25}~';
if (preg_match($regex, $yourstring, $m)) {
    $thematch = $m[0];
}
else { // No match...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM