PHP preg_match() Function
PHP Regular Expressions (PCRE)
The preg_match function performs a regular expression match.
Syntax
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
Searches subject for a match to the regular expression given by pattern.
Parameter Description:
-
$pattern: the pattern to search for, as a string.
-
$subject: the input string.
-
$matches: if the matches parameter is provided, it will be filled with the search results. $matches[0] will contain the text matched by the complete pattern, $matches[1] will contain the text matched by the first captured subgroup, and so on.
-
$flags: flags can be set to the following flag values:
PREG_OFFSET_CAPTURE: If this flag is passed, for every occurring match the appended string offset (relative to the target string) will be returned. Note: this changes the array filled into the matches parameter, so that each element becomes an array whose element 0 is the matched string and element 1 is the offset of that matched string within the target string subject.
PREG_OFFSET_CAPTURE: If this flag is passed, for every occurring match the appended string offset (relative to the target string) will be returned. Note: this changes the array filled into the matches parameter, so that each element becomes an array whose element 0 is the matched string and element 1 is the offset of that matched string within the target string subject.
-
offset: Normally, the search starts from the beginning of the target string. The optional offset parameter is used to specify starting the search from a certain position in the target string (in bytes).
Return Value
Returns the number of times pattern matches. Its value will be 0 (no match) or 1, because preg_match() stops searching after the first match. preg_match_all() differs from this in that it keeps searching subject until the end is reached. If an error occurs, preg_match() returns FALSE.
Example
Search for the text string "php":
The execution result is as follows:
查找到匹配的字符串 php。
Search for the word "web"
The execution result is as follows:
查找到匹配的字符串。
未发现匹配的字符串。
Extract the domain name from a URL
The execution result is as follows:
domain name is: runoob.com
Using named subpatterns
\w+): (?PThe execution result is as follows:
Array
(
[0] => foobar: 2008
[name] => foobar
[1] => foobar
[digit] => 2008
[2] => 2008
)