Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Storing Matched Strings

The preg_match() function has a fourth parameter that allows you to pass in an array for it to store a list of matched strings. Consider this script:

    $a = "Foo moo boo tool foo!";
    preg_match("/[A-Za-z]oo\b/i", $a, $matches);

The regexp there translates to "Match all words that start with an uppercase or lowercase letter followed by "oo" at the end of a word, case-insensitive." After running, preg_match() will place all the matched patterns in the string $a into $matches, which you can then read for your own uses.

The preg_match() function returns as soon as it finds its first match, because most of the time we only want to know whether a string exists, as opposed to how often it exists. As a result, our fourth parameter is not working as we hoped quite yet—we need another function, preg_match_all(), to get this right. This works just like preg_match()—it takes the same parameters (except in very complicated cases you are unlikely to encounter), and returns the same values. Thus, with no changes, the same code works fine with the new function:

    $a = "Foo moo boo tool foo!";
    preg_match_all("/[A-Za-z]oo\b/i", $a, $matches);
    var_dump($myarray);

This time, $matches is populated properly—but what does it contain? Many regexp writers write complicated expressions to match various parts of a given string in one line, so $matches will contain an array of arrays, with each array element containing a list of the strings the preg_match_all() found.

Line three of the script ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page