Regular expressions offer a powerful way to test strings for the presence of patterns.
They use a language all their own to describe patterns, a language that consists mostly of
symbols. PHP has several functions that use regular expressions. You may wish to turn to
Chapter 16, which describes regular expressions in detail.
boolean ereg(string pattern, string text, array matches)
The ereg function 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.
This function is discussed in depth in Chapter 16.
<?
// show User Agent
print("User Agent: $HTTP_USER_AGENT
\n");
// try to parse User Agent
if(ereg("^(.+)/([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");
}
?>
string ereg_replace(string pattern, string replacement, string
text)
Use ereg_replace to replace substrings within the text argument. Each time the
pattern matches a substring within the text argument, it is replaced with the replacement
argument. The text argument is unchanged, but the altered version is returned.