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.

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

Get Web Database Applications with PHP, and MySQL now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.