Basic regexes with preg_match() and preg_match_all()

int preg_match ( string pattern, string subject [, array matches [, int flags [, int offset]]])

int preg_match_all ( string pattern, string subject [, array matches [, int flags [, int offset]]])

Our basic regex function is preg_match() and takes two parameters: the pattern to match, and the string to match it against. Preg_match() 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 in a string. An alternative function, preg_match_all(), does not exit after the first match - we will get onto that later.

Regular expressions are formed by starting with a forward slash /, followed by a sequence of special symbols and words to match, then another slash and, optionally, a string of letters that affect the expression.

Sound complicated? Don't worry - it is complicated! We're going to break it right down, though, so hopefully it will make sense immediately. Here is a list of very basic regular expressions, strings, and whether or not a match is made:

Regex

String

Result

/php/

php

Match

php/

php

Error; you need a slash at the start

/php/

PHP

No match; regexes are case sensitive

/php/i

PHP

Match; /i means "case insensitive"

/Foo/i

FOO

Match

As you can see, "i" is the modifier to make the regex case insensitive - it will slow things down a touch, but might make your life a great deal easier.

Here is how to use preg_match() on some of those example regexes:

<?php
    if (preg_match("/php/", "php")) {
        print "Got match!\n";
    }

    if (preg_match("/php/", "PHP")) {
        print "Got match!\n";
    }

    if (preg_match("/php/i", "php")) {
        print "Got match!\n";
    }
?>

The first and third preg_match() calls will return true (the second will fail because the case is wrong and "i" is not specified), and print "Got match!"

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Novice regexes >>

Previous chapter: Regular expressions

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.