📅  最后修改于: 2020-09-29 05:50:12             🧑  作者: Mango
preg_match()函数是PHP的内置函数,它执行正则表达式匹配。此函数在字符串搜索模式,如果模式存在则返回true,否则返回false。
通常,搜索从$subject字符串参数的开头开始。可选参数$offset用于从指定位置开始搜索。
int preg_match (string $pattern, string $subject, array $matches, int $flags, int $offset)
注意:$ offset是一个可选参数,用于指定从何处开始搜索。
此函数接受五个参数,如下所述:
模式
它是一个字符串类型参数。此参数将要搜索的模式保存为字符串。
学科
此参数保存我们在其中搜索模式的输入字符串。
火柴
如果提供matchs参数,它将包含搜索结果。
matchs[0]-将保留与完整模式匹配的文本。
matchs[1]-它将包含与第一个捕获的带括号的子模式匹配的文本,依此类推。
标志
这些标志可以具有以下给出的标志:
抵消
默认情况下,搜索从$subject参数的开头开始。offset参数用于指定开始搜索的位置。它是一个可选参数。
如果pattern匹配,则preg_match()函数返回true,否则返回false。
注意:如果只想检查一个字符串是否包含在另一个字符串,请不要使用preg_match() 函数。使用strpos() 函数,因为它将更快。
输出:
Array ( [0] => Array ( [0] => javatpoint [1] => 0 ) [1] => Array ( [0] => java [1] => 0 )
[2] => Array ( [0] => t [1] => 4 ) [3] => Array ( [0] => point [1] => 5 ) )
我们可以看到上面给出的输出,以便更好地理解。
Array (
[0] => Array (
[0] => javatpoint
[1] => 0
)
[1] => Array (
[0] => java
[1] => 0
)
[2] => Array (
[0] => t
[1] => 4
)
[3] => Array (
[0] => point
[1] => 5
)
)
示例:不区分大小写的搜索
";
print_r($matches);
} else {
echo "Pattern not matched in string.";
}
?>
输出:
Pattern matched in string.
Array ( [0] => JTP )
示例:通过使用单词边界(\b)
";
} else {
echo "A match was not found. ";
}
if (preg_match("/\bweb\b/i", "PHP is a website scripting language.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
输出:
A match was found.
A match was not found.
示例:从URL中获取域名
输出:
Domain name is: javatpoint.com
[abc] | Matches a single character – a, b, or c |
[^abc] | Matches any single character but a, b, or c |
[a-z] | Matches any single character within the range a-z |
[a-zA-Z] | Any single character within the range a-z or A-Z |
^ | Start of line |
$ | End of line |
\A | Start of string |
\z | End of string |
. | Any single character |
\s | Any whitespace character |
\S | Any non-whitespace character |
\d | Any digit |
\D | Any non-digit |
\w | Any word character (letter, number, underscore) |
\W | Any non-word character |
\b | Word boundary checker |
/?/ | Starts and ends the regular expression |
(?) | Capture everything enclosed in parenthesis () |
(a|b) | a or b |
a? | Zero or one of a |
a* | Zero or more of a |
a+ | One or more of a |
a{3} | Exactly 3 of a |
a{3,} | 3 or more of a |
a{3,6} | Between 3 and 6 of a |
i | Case insensitive check |
m | Make dot match newlines |
x | Ignore whitespace in regex |