5.4 Matching over Multiple Lines


You need to write a regular expression that will match in a string containing more than one line, however, the special characters "." , "^" , and "$" do not work.

Technique

With the basic POSIX standard regular expressions provided with PHP, matching over one line is pretty hard. But the PCRE library makes this simple. Just use the Perl regular expressions with the /m or /s modifier or use both in conjunction. The /m operator enables you to match "^" and "$" next to a newline (it does not normally allow this). For example, /Mary$/m will match all occurrences of Mary before a newline (not just before the end of the string).

The /s modifier will allow the "." to match newlines as well as any other character (besides the \0 character). The "." treats a newline just like a NULL character ( \0 ) if the /s modifier is not set.

Comments

It might not be easy to match over multiple lines without PCRE installed, but it is possible. The following is a workaround:

 <?php $lines = explode ("\n", $text); foreach ($lines as $line) {     if (ereg ('Mary$', $line)) {         $matches[] = $line;     } } ?> 

However, look at the same thing implementing the PCRE library:

 <?php preg_match ("/Mary$/m", $text, $matches); ?> 

It is obvious that the PCRE solution is not only much faster but also more elegant.

Let's take a small, practical example of matching over multiple lines. The following is a small program that, when given a file, opens it, and converts all lines that start with "Heading X " to <h X > tags:

 <?php $fn = isset ($argv[0]) ? $argv[0] : 'php://stdin'; $text = @file ($fn); $text = preg_replace ("/^Heading\s+([0-5])\s*:(.*?)/m", "<h\1>\2</h\1>",         $text); print $text; ?> 

As a side note: Inside of a regular expression that uses the /s modifier, the meaning of the . operator changes to [^\n] (any character but a newline).



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net