yarek
yarek

Reputation: 12064

PHP and regex: how to preg_match on multiple line?

My HTML is:

line1
line2

line3 59800 line4
line5
line6

My goal is to capture: (25 left characters)59800(25 right characters):

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

Upvotes: 2

Views: 3787

Answers (2)

zx81
zx81

Reputation: 41848

Adding to @anubhava's answer, which is correct:

  • You don't need the i flag as there are no letters mentioned in the regex
  • The g flag doesn't exist in PHP.
  • You can also use (?s) to activate DOTALL mode, allowing the dot to match across lines

In PHP you can do this:

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

Upvotes: 1

anubhava
anubhava

Reputation: 786091

Instead of m, use the s (DOTALL) flag in your regex:

/.{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.

Upvotes: 7

Related Questions