PHP preg_match() Function
PHP Regular Expressions (PCRE)
The preg_match function is used to perform 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
$flags: flags can be set to the following flag values:
PREG_OFFSET_CAPTURE: If this flag is passed, for every occurrence of a match, the string offset (relative to the target string) will be appended. Note: This changes the array filled into the matches parameter, making each element an array where the 0th element is the matched string and the 1st element is the offset of that matched string in the target string subject.
offset: Usually, the search starts from the beginning of the target string. The optional parameter offset is used to specify starting the search from a certain position in the target string (in bytes).
Return Value
Returns the number of matches for pattern. Its value will be 0 (no match) or 1, because preg_match() stops searching after the first match. preg_match_all() is different; it continues searching subject until the end is reached. If an error occurs, preg_match() returns FALSE.
Examples
Find the text string "php":
The execution result is as follows:
查找到匹配的字符串 php。
Find the word "web"
The execution result is as follows:
Matching string found.
Get the domain name from URL
The execution result is as follows:
domain name is: example.com
Using Named Subgroups
The execution result is as follows:
Array
(
[0] => foobar: 2008
[name] => foobar
[1] => foobar
[digit] => 2008
[2] => 2008
)
Other Extensions