Basic regexps 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 regexp 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:

Regexp

String

Result

/php/

php

Match

php/

php

Error; you need a slash at the start

/php/

PHP

No match; regexps 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 regexp 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 regexps:

<?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!"

 

Next chapter: Novice regexps >>

Previous chapter: Regular expressions

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar