Sep 012014
 
Article PHP

The preg_match function in PHP can be used to find, inside a string, those substrings that match a pattern specified by means of a regular expression.

But the default behaviour of preg_match is not to match a substring that spans more than one line.

The problem

To give an example, we will write a snippet that starts with a sentence that assigns to a variable “$document” several lines of HTML code as a single string:

The title of the document can be extracted with a call to preg_match like this:

However, if we try to extract the body of the document in the same way, it does not work:

Solution 1

This problem can be solved adding the “s” modifier to the regular expression. With this modifier, the “.” wildcard character matches any possible character in the string, including newlines:

 Solution 2

Alternatively, the regular expression can be written as:

The “\s” special character matches all types of white space, including newlines, tabs, etc.

The “\S” special character matches any character not matched by “\s”.

Thus, the expression [\s\S] matches any character, and is equivalent to the expression “.” in a regexp with the “s” modifier.

—-

Index of posts related to PHP programming

 Posted by at 7:46 am

  One Response to “multiline searches with preg_match in PHP”

  1. Hi, good Article , Thanks

 Leave a Reply

(required)

(required)