===== Syntax =====
int preg_match(string $pattern, string $source, array &$matches [, int $flags [, int $offset]])
//(PHP 4, PHP 5)//
^ $pattern | A POSIX regular expression string. |
^ $source | The source string to perform the match operation against. |
^ $matches | The output of the regular expression match operation. |
^ $flags | Options for the type of pattern matching to perform (see below). |
^ $offset | Offset (character position) within the source string to start the pattern matching from. |
^ RETURNS | The total number of times the pattern matches. Since this function stops matching after the first match, the only possible results are **0** or **1**. |
**Possible values for $flags**
^ PREG_OFFSET_CAPTURE | When specified, the match value stored in **$matches** will be an array with index **0** containing the matched string and the string offset where the match occurred at index **1**.|
===== What it Does =====
Given an input string (**$source**) and regular expression (**$pattern**), this function will attempt to do a single regular expression match and populate the output string (**$matches**). The **$matches** argument is passed by reference so that it can return an array with the match results.
Unless the flag ''PREG_OFFSET_CAPTURE'' is specified, the match value returned in **$matches** will contain the entire string match in ''$matches[0]'' and any parentesized (substring) matches in ''$matches[1]'', ''$matches[2]'', etc.
===== Example =====
// match a phone number
$pattern = '|\((\d{3})\)\s+\d{3}\-\d{4}|';
// attempt to match the phone
if (preg_match($pattern, $_POST['phone'], $out)) {
// entire match is the phone number
$phone = $out[0];
// first parenthesized submatch is the areacode (\d{3})
$areacode = $out[1];
} else
// generate an error - no valid phone matched
$err = 'Please enter a valid phone number like (xxx) xxx-xxxx';