preg_match
(PHP 4, PHP 5, PHP 7, PHP 8)
Perform a regular expression match
Description
Searches subject for a match to the regular expression given in pattern.
Parameters
patternThe pattern to search for, as a string.
subjectThe input string.
matchesIf
matchesis provided, then it is filled with the results of search.$matches[0]will contain the text that matched the full pattern,$matches[1]will have the text that matched the first captured parenthesized subpattern, and so on.flagsflagscan be a combination of the following flags:PREG_OFFSET_CAPTUREIf this flag is passed, for every occurring match the appendant string offset (in bytes) will also be returned. Note that this changes the value of
matchesinto an array where every element is an array consisting of the matched string at offset0and its string offset intosubjectat offset1.php<?php preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?>The above example will output:
outputArray ( [0] => Array ( [0] => foobarbaz [1] => 0 ) [1] => Array ( [0] => foo [1] => 0 ) [2] => Array ( [0] => bar [1] => 3 ) [3] => Array ( [0] => baz [1] => 6 ) )PREG_UNMATCHED_AS_NULLIf this flag is passed, unmatched subpatterns are reported as null and are always included in the results (including trailing ones). Without this flag, unmatched subpatterns that are followed by a matched subpattern are reported as an empty
string, while trailing unmatched subpatterns are omitted from the results entirely.php<?php preg_match('/(a)(b)*(c)/', 'ac', $matches); var_dump($matches); preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL); var_dump($matches); // Trailing unmatched subpatterns: preg_match('/(a)(b)?(c)?/', 'a', $matches); var_dump($matches); preg_match('/(a)(b)?(c)?/', 'a', $matches, PREG_UNMATCHED_AS_NULL); var_dump($matches); ?>The above example will output:
outputarray(4) { [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> string(0) "" [3]=> string(1) "c" } array(4) { [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> NULL [3]=> string(1) "c" } array(2) { [0]=> string(1) "a" [1]=> string(1) "a" } array(4) { [0]=> string(1) "a" [1]=> string(1) "a" [2]=> NULL [3]=> NULL }
offsetNormally, the search starts from the beginning of the subject string. The optional parameter
offsetcan be used to specify the alternate place from which to start the search (in bytes).NoteUsing
offsetis not equivalent to passingsubstr($subject, $offset)topreg_match()in place of the subject string, becausepatterncan contain assertions such as ^, $ or (?<=x). Compare:php<?php $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); print_r($matches); ?>The above example will output:
outputArray ( )while this example
php<?php $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?>will produce
outputArray ( [0] => Array ( [0] => def [1] => 0 ) )Alternatively, to avoid using
substr(), use the\Gassertion rather than the^anchor, or theAmodifier; both of which do not work with theoffsetparameter.
Return Values
preg_match() returns 1 if the pattern matches given subject, 0 if it does not,Falseforfailure.
Falseproblem
Errors/Exceptions Warning
Changelog
| Version | Description |
|---|---|
| 7.4.0 | When the PREG_UNMATCHED_AS_NULL flag is used, trailing unmatched capturing groups are now also included in the result with the value null (or [null, -1] when PREG_OFFSET_CAPTURE is also used), so that $matches always has the same size. Previously, they were omitted. |
| 7.2.0 | The PREG_UNMATCHED_AS_NULL is now supported for the flags parameter. |
Examples
Find the string of text "php"
<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>Find the word "web"
<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
echo "\n";
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>Getting the domain name out of a URL
<?php
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
"http://www.php.net/index.html", $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>The above example will output:
domain name is: php.netUsing named subpattern
<?php
$str = 'foobar: 2008';
preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);
/* Alternative */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);
print_r($matches);
?>The above example will output:
Array
(
[0] => foobar: 2008
[name] => foobar
[1] => foobar
[digit] => 2008
[2] => 2008
)Notes
Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster.