preg_match()是PHP中用于执行正则表达式匹配的核心函数,能够检查字符串是否与指定模式匹配。该函数基于PCRE(Perl兼容正则表达式)库,提供强大的模式匹配能力。
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
preg_match()返回模式匹配的次数(0或1),因为它在第一次匹配后停止搜索。如果发生错误返回FALSE。
$email = "test@example.com";
if (preg_match('/^[\w\-\.]+@([\w\-]+\.)+[\w\-]{2,4}$/', $email)) {
echo "邮箱格式正确";
} else {
echo "邮箱格式错误";
}
$url = "https://www.example.com/page";
if (preg_match('/https?:\/\/([\w\-\.]+)/', $url, $matches)) {
echo "域名: " . $matches[1];
}
$phone = "13800138000";
if (preg_match('/^1[3-9]\d{9}$/', $phone)) {
echo "手机号格式正确";
}
使用i修饰符进行不区分大小写匹配:/pattern/i
使用m修饰符:/pattern/m 使^和$匹配每行的开头和结尾
$result = @preg_match($pattern, $subject);
if ($result === false) {
echo "正则表达式有误";
}
preg_match()是PHP中处理正则表达式匹配的强大工具,熟练掌握其用法能够大大提高字符串处理的效率和准确性。在实际开发中,结合具体业务需求选择合适的正则模式,并注意错误处理和性能优化。