Chapter 15. Regular Expressions

Regular expressions, usually referred to as regexps, offer you more power over your strings, but are tricky to learn because they use complicated syntax. Regexps can:

  • Replace text

  • Test for a pattern within a string

  • Extract a substring from within a string

We'll be looking at all three of these uses in this chapter, as well as providing a comprehensive list of the different expressions you can use to work with all kinds of strings.

You should know that the set of string functions covered in Chapter 7 are faster, easier to read, and less hassle to use than regular expressions; you should only use regular expressions if you have a particular need. PHP contains two ways to perform regular expressions, known as POSIX-extended and Perl-Compatible Regular Expressions (PCRE). The PCRE functions are more powerful than the POSIX ones, and faster too, so we will be using the PCRE functions here.

Basic Regexps with preg_match() and preg_match_all()

The basic regexp function is preg_match() and it takes two parameters: the pattern to match and the string to match it against. It will apply the regular expression in parameter one to the string in parameter two and see whether it finds a match—if it does, it will return 1; otherwise, 0. The reason it returns 1 is because regular expressions return the number of matches found, but preg_match(), for speed reasons, returns as soon as it finds the first match—this means it is very quick to check whether a pattern exists ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.