Modifiers in regular expression patterns in php

preg_match is used to perform a regular expression match.

if you want to match patterns across multiple lines then you need to use PCRE modifiers.
$str = 'Test
multi';
the following code will not work for multiple lines
if (preg_match('/^multi$/', $str))
 echo 'Matched';
You need the following code for multiple lines
if (preg_match('/^multi$/m', $str))
 echo 'Matched';

m (PCRE_MULTILINE) modiefier:

By default, PCRE treats the subject string as consisting of a single “line” of characters (even if it actually contains several newlines). The “start of line” metacharacter (^) matches only at the start of the string, while the “end of line” metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl. When this modifier is set, the “start of line” and “end of line” constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl’s /m modifier. If there are no “\n” characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

Reference: php.net

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s