Приглашаем посетить
Техника (find-info.ru)

Section 15.5.  Storing Matched Strings

Previous
Table of Contents
Next

15.5. 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 yetwe 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 properlybut 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 calls var_dump( ) on the array, so you can see the matches preg_match_all( ) picked up. The var_dump( ) function simply outputs the contents of the variable(s) passed to it for closer inspection, and is particularly useful with arrays and objects. You can read more on var_dump( ) later on.


Previous
Table of Contents
Next