Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

The preg_grep function compares the elements of the data argument that match the
given pattern.


boolean preg_match(string pattern, string text, array matches)


The preg_match function is the equivalent of ereg. It evaluates the pattern argument
as a regular expression and attempts to find matches in the text argument. If the optional
matches argument is supplied, each match will be added to the array. TRUE is returned
if at least one match is made, FALSE otherwise.


The first element in the matches array, with an index of zero, will contain the match for
the entire regular expression. Subsequent elements of matches will contain the matches
for subexpressions. These are the expressions enclosed in parentheses in the example.


<?


// show User Agent
print("User Agent: $HTTP_USER_AGENT
\n");


// try to parse User Agent
if(preg_match("/^(.+)/([0-9]).([0-9]+)/",
$HTTP_USER_AGENT, $matches))
{
print("Full match: $matches[0]
\n");
print("Browser: $matches[1]
\n");
print("Major Version: $matches[2]
\n");
print("Minor Version: $matches[3]
\n");
}
else
{
print("User Agent not recognized");
}
?>


integer preg_match_all (string pattern, string text, array
matches, integer order)


The preg_match_all function operates similarly to preg_match. A pattern is
evaluated against the text argument, but instead of stopping when a match is found,
subsequent matches are sought. The matches argument is required and will receive a
two-dimensional array. The method for filling this array is determined by the order
argument. It may be set with two constants, either PREG_PATTERN_ORDER, the default,
or PREG_SET_ORDER. The number of matches against the full pattern is returned.

Free download pdf