PHP 表单 - 验证邮件和URL
核对使用 preg_match() 正则表达式与 filter_var() 校验姓名、电子邮件和 URL 的语法、捕获行为与未锚定正则边界差异。
学完这一章,你能够
- 核对使用 preg_match() 正则表达式与 filter_var() 校验姓名、电子邮件和 URL 的语法、捕获行为与未锚定正则边界差异。
使用 preg_match() 验证姓名字段
确认必需字段非空后,还需校验格式合法性。姓名字段采用 `preg_match("/^[a-zA-Z ]*$/", $name)` 检查字符串是否全部由英文字母与空格组成,未匹配时写入“只允许字母和空格”。`preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0)` 成功匹配返回 `1`、未匹配返回 `0`、出错返回 `false`,传入 `$matches` 时 `$matches[0]` 保存完整匹配文本,`$matches[1]` 起保存各捕获分组。本站 PHP 8.4.27 实测 `"Alice Lin"` 返回 `1`、`"Alice123"` 与 `"Bob-Wu"` 返回 `0`,捕获分组返回 `['Alice Lin', 'Alice', 'Lin']`。
验证电子邮件与 URL 格式
邮箱基础示例使用 `preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)` 检测是否包含用户名、`@`、域名及后缀。本站实测揭示了未锚定正则的关键差异:对 `"dev@example.org invalid"`(含非法尾部空格)未锚定正则仍误判为 `true`,而 PHP 内置 `filter_var($email, FILTER_VALIDATE_EMAIL)` 准确拒绝(`false`)且同时支持 `user+tag@sub.example.org` 这类标准子地址(`true`);实际项目应优先使用 `filter_var()`。
网址校验示例采用支持连字符 `-` 与 `www.` 前缀的正则表达式 `/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i`。本站实测该正则允许 `https://blue-sky.example.org/php-guide?id=28` 与 `www.blue-sky.example.org` 并拒绝 `not-a-valid-url`;而 `filter_var($url, FILTER_VALIDATE_URL)` 要求显式协议头,故接受带 `https://` 的完整网址而拒绝省略协议头的 `www.` 写法。
将判空逻辑与姓名、邮箱、URL 格式校验合并后,每个必填项先经 `empty()` 判定再执行格式检查,可选的网址字段仅在非空时才触发正则检验。本站完整实测同时含非法姓名 `Alice99`、非法邮箱 `bad@` 和非法网址 `ftp_broken` 的载荷一次收集 3 项错误,规范输入则全部通过(`valid=true`)。
preg_match() 函数说明
| 函数 | 语法与捕获行为 |
|---|---|
| preg_match() | 执行 PCRE 正则匹配:int|false preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0);匹配时 $matches[0] 为整体匹配结果,$matches[1..n] 为对应捕获子组。 |
运行姓名/邮箱/URL 正则校验、preg_match 捕获与 filter_var 对比实验
<?php
declare(strict_types=1);
function test_input(string $data): string
{
return htmlspecialchars(stripslashes(trim($data)), ENT_QUOTES, 'UTF-8');
}
$cases = [];
// Case 1: Name regex validation and preg_match capture group behavior
(function () use (&$cases): void {
$pattern = '/^[a-zA-Z ]*$/';
$matches = [];
$mCapture = preg_match('/^([a-zA-Z]+)\s+([a-zA-Z]+)$/', 'Alice Lin', $matches);
$actual = [
'valid_name' => preg_match($pattern, 'Alice Lin'),
'digits_rejected' => preg_match($pattern, 'Alice123'),
'hyphen_rejected' => preg_match($pattern, 'Bob-Wu'),
'capture_return' => $mCapture,
'capture_groups' => $matches,
];
$expected = [
'valid_name' => 1,
'digits_rejected' => 0,
'hyphen_rejected' => 0,
'capture_return' => 1,
'capture_groups' => ['Alice Lin', 'Alice', 'Lin'],
];
$cases[] = [
'name' => 'validate_name_regex',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 2: Email validation via regex vs filter_var(FILTER_VALIDATE_EMAIL)
(function () use (&$cases): void {
$emailRegex = '/([\w\-]+\@[\w\-]+\.[\w\-]+)/';
$anchoredRegex = '/^[\w\-]+\@[\w\-]+\.[\w\-]+$/';
$samples = [
'standard' => 'dev@example.org',
'missing_domain' => 'bad-email@',
'trailing_garbage' => 'dev@example.org invalid',
'plus_subaddress' => 'user+tag@sub.example.org',
];
$actual = [];
foreach ($samples as $label => $addr) {
$actual[$label] = [
'unanchored_regex' => preg_match($emailRegex, $addr) === 1,
'anchored_regex' => preg_match($anchoredRegex, $addr) === 1,
'filter_var' => filter_var($addr, FILTER_VALIDATE_EMAIL) !== false,
];
}
$expected = [
'standard' => ['unanchored_regex' => true, 'anchored_regex' => true, 'filter_var' => true],
'missing_domain' => ['unanchored_regex' => false, 'anchored_regex' => false, 'filter_var' => false],
'trailing_garbage' => ['unanchored_regex' => true, 'anchored_regex' => false, 'filter_var' => false],
'plus_subaddress' => ['unanchored_regex' => true, 'anchored_regex' => false, 'filter_var' => true],
];
$cases[] = [
'name' => 'validate_email_regex_and_filter',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 3: URL validation with hyphen-tolerant regex vs filter_var(FILTER_VALIDATE_URL)
(function () use (&$cases): void {
$urlRegex = '/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i';
$samples = [
'https_hyphen' => 'https://blue-sky.example.org/php-guide?id=28',
'www_only' => 'www.blue-sky.example.org',
'invalid_text' => 'not-a-valid-url',
];
$actual = [];
foreach ($samples as $label => $url) {
$actual[$label] = [
'regex' => preg_match($urlRegex, $url) === 1,
'filter_var' => filter_var($url, FILTER_VALIDATE_URL) !== false,
];
}
$expected = [
'https_hyphen' => ['regex' => true, 'filter_var' => true],
'www_only' => ['regex' => true, 'filter_var' => false],
'invalid_text' => ['regex' => false, 'filter_var' => false],
];
$cases[] = [
'name' => 'validate_url_regex_and_filter',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 4: Full 5-field validation flow (required + name/email/URL format checks)
(function () use (&$cases): void {
$validateAll = static function (array $post): array {
$nameErr = $emailErr = $websiteErr = $genderErr = '';
$name = $email = $website = $comment = $gender = '';
if (empty($post['name'])) {
$nameErr = '名字是必需的';
} else {
$name = test_input((string)$post['name']);
if (!preg_match('/^[a-zA-Z ]*$/', $name)) {
$nameErr = '只允许字母和空格';
}
}
if (empty($post['email'])) {
$emailErr = '邮箱是必需的';
} else {
$email = test_input((string)$post['email']);
if (!preg_match('/([\w\-]+\@[\w\-]+\.[\w\-]+)/', $email)) {
$emailErr = '非法邮箱格式';
}
}
if (!empty($post['website'])) {
$website = test_input((string)$post['website']);
if (!preg_match('/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i', $website)) {
$websiteErr = '非法的 URL 地址';
}
}
if (!empty($post['comment'])) {
$comment = test_input((string)$post['comment']);
}
if (empty($post['gender'])) {
$genderErr = '性别是必需的';
} else {
$gender = test_input((string)$post['gender']);
}
return [
'errors' => compact('nameErr', 'emailErr', 'websiteErr', 'genderErr'),
'valid' => ($nameErr === '' && $emailErr === '' && $websiteErr === '' && $genderErr === ''),
];
};
$actual = [
'invalid_submission' => $validateAll([
'name' => 'Alice99',
'email' => 'bad@',
'website' => 'ftp_broken',
'gender' => 'female',
]),
'valid_submission' => $validateAll([
'name' => 'Alice Lin',
'email' => 'alice@example.org',
'website' => 'https://blue-sky.example.org/docs',
'comment' => 'ok',
'gender' => 'female',
]),
];
$expected = [
'invalid_submission' => [
'errors' => [
'nameErr' => '只允许字母和空格',
'emailErr' => '非法邮箱格式',
'websiteErr' => '非法的 URL 地址',
'genderErr' => '',
],
'valid' => false,
],
'valid_submission' => [
'errors' => [
'nameErr' => '',
'emailErr' => '',
'websiteErr' => '',
'genderErr' => '',
],
'valid' => true,
],
];
$cases[] = [
'name' => 'combined_form_validation',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
- 核对姓名正则匹配与分组捕获、未锚定邮箱正则 vs filter_var 差异、支持连字符的 URL 正则行为以及五字段联合校验结果。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
当前源码 SHA256:12d30cfb8c9c1f0d0151f18a639f6fbe0f4701fce820a964ac1af48d24d95b4d
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
ZIP SHA256:b22e15a133b7625893a4f15955417cbb3727ac7da424df5a98d929336957f6e5
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么生产环境校验邮箱地址更推荐 filter_var($email, FILTER_VALIDATE_EMAIL) 而不是简单的未锚定正则 /([\w\-]+\@[\w\-]+\.[\w\-]+)/?
展开参考解答
未锚定正则只要字符串中任意子串形如 a@b.c 就会返回 1(如 "dev@example.org invalid" 被误放行),而简单锚定正则又会误杀合法的 + 号子地址;filter_var 遵循 RFC 邮箱规范判断整串合法性,更准确可靠。