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 ...

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.