Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
The first advanced area we will look at is that of regular expressions. Regular expressions provide a more advanced way to match patterns within a given string. Although there are many string functions available within PHP, there are still some tasks that you may want to perform that only a regular expression can accomplish. There are two types of regular expressions: Portable Operating System Interface for UniX (POSIX) and Perl-compatible. Because the Perl-compatible expressions are a little faster and more robust, we will only look at them here. There are three general uses for regular expressions: string matching, string substituting, and string splitting.
Let’s look at string matching first. When you are looking for a certain string or pattern within a provided string, you have to delimit the pattern. You generally do this with the forward slash character (/), but you can use any other nonalphanumeric character (other than the backslash) to do the same thing. So, if you are looking for a string pattern of “fox,” you could set it up as /fox/ or #fox#, as long as you use the same characters on both ends of the pattern and they are not among the character pattern for which you are looking (e.g., if your pattern was fox#y, you would want to use /fox#y/ or {fox#y}, but not #fox#y#). The function to use for matching is preg_match: if a result is found, a 1 is returned (because it stops searching after the first occurrence found), and if nothing is found, a 0 is returned (“false” is returned if an error occurs). Consider the string: “the quick brown fox jumps over the lazy dog.” We will use that to do some pattern matching. Here is the first sample: