home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Web Database Applications with PHP \& MySQLWeb Database Applications with PHP \& MySQLSearch this book

2.7. Regular Expressions

In this section we show how regular expressions can achieve more sophisticated pattern matching to find, extract, and even replace complex substrings within a string.

While regular expressions provide capabilities beyond those described in the last section, complex pattern matching isn't as efficient as simple string comparisons. The functions described in the last section are more efficient than those that use regular expressions and should be used if complex pattern searches aren't required.

This section starts with a brief description of the POSIX regular expression syntax. This isn't a complete description of all the capabilities, but we do provide enough details to create quite powerful regular expressions. The second half of the section describes the functions that use POSIX regular expressions. Examples of regular expressions can be found in this section and in Chapter 7.

2.7.1. Regular Expression Syntax

A regular expression follows a strict syntax to describe patterns of characters. PHP has two sets of functions that use regular expressions: one set supports the Perl Compatible Regular Expression (PCRE) syntax, while the other supports the POSIX extended regular expression syntax. In this book we use the POSIX functions.

To demonstrate the syntax of regular expressions, we introduce the function ereg():

boolean ereg(string pattern, string subject [, array var])

ereg( ) returns true if the regular expression pattern is found in the subject string. We discuss how the ereg( ) function can extract values into the optional array variable var later in this section.

The following trivial example shows how ereg() is called to find the literal pattern "cat" in the subject string "raining cats and dogs":

// prints "Found a cat"
if (ereg("cat", "raining cats and dogs"))
  echo "Found 'cat'";

The regular expression "cat" matches the subject string, and the fragment prints "Found 'cat'".

2.7.1.4. Optional and repeating characters

By following a character in a regular expression with a ?, *, or + operator, the pattern matches zero or one, zero to many, or one to many occurrences of the character, respectively.

The ? operator allows zero or one occurrence of a character, so the expression:

 ereg("pe?p", $var) 

matches either "pep" or "pp", but not the string "peep". The * operator allows zero or many occurrences of the "o" in the expression:

 ereg("po*p", $var) 

and matches "pp", "pop", "poop", "pooop", and so on. Finally, the + operator allows one to many occurrences of "b" in the expression:

 ereg("ab+a", $var)

so while strings such as "aba", "abba", and "abbba" match, "aa" doesn't.

The operators ?, *, and + can also be used with a wildcard or a list of characters. The following examples show how:

$var = "www.rmit.edu.au";

// True for strings that start with "www" 
// and end with "au"
$matches = ereg('^www.*au$', $var); // true


$hexString = "x01ff";

// True for strings that start with 'x' 
// followed by at least one hexadecimal digit
$matches = ereg('x[0-9a-fA-F]+$', $hexString); // true

The first example matches any string that starts with "www" and ends with "au"; the pattern ".*" matches a sequence of any characters, including a blank string. The second example matches any sequence that starts with the character "x" followed by one or more characters from the list [0-9a-fA-F].

A fixed number of occurrences can be specified in braces. for example, the pattern "[0-7]{3}" matches three-character numbers that contain the digits 0 through 7:

$valid = ereg("[0-7]{3}", "075"); // true
$valid = ereg("[0-7]{3}", "75");  // false

The braces syntax also allows the minimum and maximum occurrences of a pattern to be specified as demonstrated in the following examples:

$val = "58273";

// true if $val contains numerals from start to end
// and is between 4 and 6 characters in length
$valid = ereg('^[0-9]{4,6}$', $val); // true

$val = "5827003";
$valid = ereg('^[0-9]{4,6}$', $val); // false

// Without the anchors at the start and end, the 
// matching pattern "582768" is found
$val = "582768986456245003";

$valid = ereg("[0-9]{4,6}", $val);   // true

2.7.1.5. Groups

Subpatterns in a regular expression can be grouped by placing parentheses around them. This allows the optional and repeating operators to be applied to groups rather than just a single character. For example, the expression:

 ereg("(123)+", $var) 

matches "123", "123123", "123123123", etc. Grouping characters allows complex patterns to be expressed, as in the following example that matches a URL:

// A simple, incomplete, HTTP URL regular expression that doesn't allow numbers
$pattern = '^(http://)?[a-zA-Z]+(\.[a-zA-z]+)+$';

$found = ereg($pattern, "www.ora.com"); // true

The regular expression assigned to $pattern includes both the start and end anchors, ^ and $, so the whole subject string, "www.ora.com" must match the pattern. The start of the pattern is the optional group of characters "http://", as specified by "(http://)?". This doesn't match any of the subject string in the example but doesn't rule out a match, because the "http://" pattern is optional. Next the "[a-zA-Z]+" pattern specifies one or more alpha characters, and this matches "www" from the subject string. The next pattern is the group "(\.[a-zA-z]+)". This pattern must start with a period—the wildcard meaning of . is escaped with the backslash—followed by one or more alphabetic characters. The pattern in this group is followed by the + operator, so the pattern must occur at least once in the subject and can repeat many times. In the example, the first occurrence is ".ora" and the second occurrence is ".com".

Groups can also define subpatterns when ereg( ) extracts values into an array. We discuss the use of ereg( ) to extract values later in this section.

2.7.1.7. Escaping special characters

We've already discussed the need to escape the special meaning of characters used as operators in a regular expression. However, when to escape the meaning depends on how the character is used. Escaping the special meaning of a character is done with the backslash character as with the expression "2\+3, which matches the string "2+3". If the + isn't escaped, the pattern matches one or many occurrences of the character 2 followed by the character 3. Another way to write this expression is to express the + in the list of characters as "2[+]3". Because + doesn't have the same meaning in a list, it doesn't need to be escaped in that context. Using character lists in this way can improve readability. The following examples show how escaping is used and avoided:

// need to escape ( and )
$phone = "(03) 9429 5555";
$found = ereg("^\([0-9]{2,3}\)", $phone); // true

// No need to escape (*.+?)| within parentheses
$special = "Special Characters are (, ), *, +, ?, |";
$found = ereg("[(*.+?)|]", $special); // true

// The back-slash always needs to be quoted to match
$backSlash = 'The backslash \ character';
$found = ereg('^[a-zA-Z \\]*$', $backSlash); //true

// Don't need to escape the dot within parentheses
$domain = "www.ora.com";
$found = ereg("[.]com", $domain); //true

Another complication arises due to the fact that a regular expression is passed as a string to the regular expression functions. Strings in PHP can also use the backslash character to escape quotes and to encode tabs, newlines, etc. Consider the following example, which matches a backslash character:

// single-quoted string containing a backslash
$backSlash = '\ backslash';

// Evaluates to true 
$found = ereg("^\\\\ backslash\$", $backSlash);

The regular expression looks quite odd: to match a backslash, the regular expression function needs to escape the meaning of backslash, but because we are using a double-quoted string, each of the two backslashes needs to be escaped. The last complication is that PHP interprets the $ character as the beginning of a variable name, so we need to escape that. Using a single-quoted string can help make regular expressions easier to read and write.

2.7.2. Regular Expression Functions

PHP has several functions that use POSIX regular expressions to find and extract substrings, replace substrings, and split a string into an array. The functions to perform these tasks come in pairs: a case-sensitive version and a case-insensitive version. While case-sensitive regular expressions can be written, the case-insensitive versions of these functions allow shorter regular expressions.

2.7.2.1. Finding and extracting values

The ereg( ) function, and the case-insensitive version eregi( ), are defined as:

boolean ereg(string pattern, string subject [, array var])
boolean eregi(string pattern, string subject [, array var])

Both functions return true if the regular expression pattern is found in the subject string. An optional array variable var can be passed as the third argument; it is populated with the portions of subject that are matched by up to nine grouped subexpressions in pattern. Both functions return false if the pattern isn't found in the subject.

To extract values from a string into an array, patterns can be arranged in groups contained by parentheses in the regular expression. The following example shows how the year, month, and day components of a date can be extracted into an array:

$parts = array( );
$value = "2001-09-07";
$pattern = '^([0-9]{4})-([0-9]{2})-([0-9]{2})$';

ereg($pattern, $value, $parts);

// Array ([0]=> 2001-09-07 [1]=>2001 [2]=>09 [3]=>07 
print_r($parts); 

The expression:

'^([0-9]{4})-([0-9]{2})-([0-9]{2})$'

matches dates in the format YYYY-MM-DD. After calling ereg( ), $parts[0] is assigned the portion of the string that matches the whole regular expression—in this case, the whole string 2001-09-07. The portion of the date that matches each group in the expression is assigned to the following array elements: $parts[1] contains the year matched by ([0-9]{4}), $parts[2] contains the month matched by ([0-9]{2}), and $parts[3] contains the day matched by "([0-9]{2})".

2.7.2.2. Replacing substrings

The following functions create new strings by replacing substrings:

string ereg_replace(string pattern, string replacement, string source)
string eregi_replace(string pattern, string replacement, string source)

They create a new string by replacing substrings of the source string that match the regular expression pattern with a replacement string. These functions are similar to the str_replace( ) function described earlier in the Section 2.6 section, except that the replaced substrings are identified using a regular expression. Consider the examples:

$source = "The  quick\tbrown\n\tfox jumps";

// prints "The quick brown fox"
echo ereg_replace("[ \t\n]+", " ", $source);

$source = "\xf6 The  quick\tbrown\n\tfox jumps\x88";

// replace all non-printable characters with a space
echo ereg_replace("[^ -~]+", " ", $source);

The second example uses the regular expression "[^ -~]+" to match all characters except those that fall between the space character and the tilde character in the ASCII table. This represents almost all the printable 7-bit characters.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.