PHP Regular Expression Types

There are two sets of PHP functions that facilitate regular expressions. The preferred set is the PCRE (Perl-Compatible Regular Expressions) library. You can identify these functions because, in PHP, they start with the prefix preg. Examples of PCRE regular expression functions are preg_replace(), preg_split(), preg_match(), and preg_match_all(). The other regular expression family available within PHP is POSIX (Extended Regular Expressions). These functions begin with the prefix ereg and are included in PHP primarily for backward compatibility. The ereg instructions have been deprecated since PHP 5.3.0 and are mentioned here only because you’ll be exposed to them as you explore PHP regular expression instructions online. We will describe only the PCRE regular expressions in this chapter, and for simplicity, we will also limit our discussion to the most frequently used functions within PHP’s implementation of PCRE.[17]

The most common uses for regular expressions are these:

Next we’ll discuss the functions that use the same simple pattern to perform all of these tasks.

You may have noticed that these regular expression functions bear a resemblance to PHP built-in functions or the parsing functions found in LIB_parse. For example:

As you will continue to discover, there are usually multiple ways to accomplish a single string manipulation, and many of the solutions can be performed with, or without, using regular expressions.

The second thing to note is that the power of regular expressions is not found in the functions that operate on patterns but in the patterns themselves. So far, you’ve only seen patterns that match a single condition. But regular expressions are much more useful when they contain complex patterns that match a variety of situations.



[17] The entire PHP PCRE manual is available at http://us.php.net/manual/en/ref.pcre.php.

[18] In fact, as you read in the previous chapter, parse_array() is merely a wrapper for preg_match_all().