1. 正则表达式基础概念
正则表达式(Regular Expression)是一种强大的文本处理工具,它使用特定的模式来描述、匹配一系列符合某个句法规则的字符串。在PHP中,正则表达式被广泛应用于表单验证、数据提取、文本替换等场景。
1.1 正则表达式的基本组成
正则表达式由普通字符(如字母a-z)和特殊字符(称为”元字符”)组成。以下是一些基本的元字符:
.
:匹配除换行符外的任意单个字符
*
:匹配前面的子表达式零次或多次
+
:匹配前面的子表达式一次或多次
?
:匹配前面的子表达式零次或一次
^
:匹配字符串的开始位置
$
:匹配字符串的结束位置
[]
:字符类,匹配方括号中的任意一个字符
[^]
:否定字符类,匹配除了方括号中字符的任意字符
|
:选择,匹配|左右任意一个表达式
()
:分组,将括号内的表达式作为一个整体
{n}
:精确匹配n次
{n,}
:至少匹配n次
{n,m}
:匹配n到m次
1.2 PHP中的正则表达式函数
PHP提供了两组正则表达式函数:PCRE(Perl Compatible Regular Expressions)和POSIX扩展。PCRE函数更强大且常用,主要包括:
preg_match()
:执行一个正则表达式匹配
preg_match_all()
:执行一个全局正则表达式匹配
preg_replace()
:执行一个正则表达式的搜索和替换
preg_filter()
:执行一个正则表达式搜索和替换
preg_split()
:通过一个正则表达式分隔字符串
preg_grep()
:返回匹配模式的数组条目
preg_quote()
:转义正则表达式字符
2. 基础模式匹配
2.1 简单字符串匹配
2.2 不区分大小写的匹配
2.3 匹配字符串开始或结束位置
2.4 使用字符类
2.5 使用预定义字符类
3. 量词与重复模式
3.1 基本量词
3.2 指定次数的量词
3.3 贪婪、懒惰与占有量词
/’;
$string = ‘
‘;
preg_match($pattern, $string, $matches);
echo “贪婪匹配结果: ” . $matches[0] . “\n”; // 输出:
// 懒惰量词(非贪婪):尽可能少地匹配
$pattern = ‘/<.*?>/’;
$string = ‘
‘;
preg_match($pattern, $string, $matches);
echo “懒惰匹配结果: ” . $matches[0] . “\n”; // 输出:
// 占有量词:尽可能多地匹配,但不回溯
$pattern = ‘/<.*+>/’;
$string = ‘
‘;
if (preg_match($pattern, $string, $matches)) {
echo “占有匹配结果: ” . $matches[0] . “\n”;
} else {
echo “占有匹配失败!\n”; // 输出: 占有匹配失败!
}
?>
4. 分组与捕获
4.1 基本分组
4.2 非捕获分组
4.3 命名捕获分组
)创建命名捕获分组
$pattern = ‘/(?P
$string = ‘2023-07-15’;
if (preg_match($pattern, $string, $matches)) {
echo “完整匹配: ” . $matches[0] . “\n”; // 输出: 2023-07-15
echo “年份: ” . $matches[‘year’] . “\n”; // 输出: 2023
echo “月份: ” . $matches[‘month’] . “\n”; // 输出: 07
echo “日期: ” . $matches[‘day’] . “\n”; // 输出: 15
}
?>
4.4 反向引用
\w+)\s+(?P=word)/’;
$string = ‘world world’;
if (preg_match($pattern, $string, $matches)) {
echo “匹配成功: ” . $matches[0] . “\n”; // 输出: world world
echo “单词: ” . $matches[‘word’] . “\n”; // 输出: world
}
?>
5. 常见的数据验证示例
5.1 验证电子邮件地址
5.2 验证电话号码
5.3 验证URL
5.4 验证IP地址
5.5 验证日期格式
5.6 验证密码强度
= $minLength;
// 包含至少一个大写字母
$uppercaseCheck = preg_match(‘/[A-Z]/’, $password);
// 包含至少一个小写字母
$lowercaseCheck = preg_match(‘/[a-z]/’, $password);
// 包含至少一个数字
$numberCheck = preg_match(‘/[0-9]/’, $password);
// 包含至少一个特殊字符
$specialCharCheck = preg_match(‘/[!@#$%^&*()\-_=+{};:,<.>]/’, $password);
return $lengthCheck && $uppercaseCheck && $lowercaseCheck && $numberCheck && $specialCharCheck;
}
// 测试
$passwords = [
‘Password123!’,
‘weak’,
‘onlylowercase’,
‘ONLYUPPERCASE’,
‘NoSpecialChars123’,
‘12345678’,
‘!@#$%^&*’,
‘Short1!’,
‘GoodPassword123!’
];
foreach ($passwords as $password) {
echo $password . ” 是” . (validatePasswordStrength($password) ? “强的” : “弱的”) . “密码\n”;
}
?>
6. 文本处理技巧
6.1 提取所有电子邮件地址
6.2 提取所有URL
6.3 移除HTML标签
]*>/’;
return preg_replace($pattern, ”, $html);
}
$html = “
标题
这是一个示例文本。
“;
$plainText = stripHtmlTags($html);
echo “原始HTML:\n” . $html . “\n\n”;
echo “移除HTML标签后的文本:\n” . $plainText . “\n”;
?>
6.4 高亮搜索关键词
$1‘;
$text = preg_replace($pattern, $replacement, $text);
}
return $text;
}
$text = “PHP是一种广泛使用的服务器端脚本语言,特别适合Web开发。PHP可以嵌入HTML中,也可以用于命令行脚本和桌面应用程序。”;
$keywords = [“PHP”, “Web”, “HTML”];
$highlightedText = highlightKeywords($text, $keywords);
echo “高亮关键词后的文本:\n” . $highlightedText . “\n”;
?>
6.5 格式化电话号码
格式化: ” . formatPhoneNumber($phone) . “\n”;
}
?>
6.6 验证和格式化信用卡号
19) {
return false;
}
// 使用Luhn算法验证信用卡号
$sum = 0;
$length = strlen($digits);
for ($i = 0; $i < $length; $i++) {
$digit = (int)$digits[$length - $i - 1];
if ($i % 2 === 1) {
$digit *= 2;
if ($digit > 9) {
$digit -= 9;
}
}
$sum += $digit;
}
if ($sum % 10 !== 0) {
return false;
}
// 格式化信用卡号(每4位一组,用空格分隔)
return preg_replace(‘/(\d{4})/’, ‘$1 ‘, $digits);
}
$cardNumbers = [
‘4111111111111111’, // Visa测试卡号
‘5500000000000004’, // MasterCard测试卡号
‘340000000000009’, // American Express测试卡号
‘6011000000000004’, // Discover测试卡号
‘4111-1111-1111-1111’, // 带分隔符的Visa卡号
‘4111111111111112’, // 无效的卡号
‘1234567890123456’ // 无效的卡号
];
foreach ($cardNumbers as $cardNumber) {
$formatted = validateAndFormatCreditCard($cardNumber);
if ($formatted !== false) {
echo $cardNumber . ” 是有效的信用卡号,格式化后: ” . $formatted . “\n”;
} else {
echo $cardNumber . ” 是无效的信用卡号\n”;
}
}
?>
7. 高级正则表达式技巧
7.1 使用断言
hello [1] => hello )
// 负向先行断言 (?!)
// 匹配后面不跟着”world”的”hello”
$pattern = ‘/hello(?!world)/’;
$string = ‘helloworld helloworlds hellothere’;
preg_match_all($pattern, $string, $matches);
echo “\n负向先行断言匹配结果: “;
print_r($matches[0]); // 输出: Array ( [0] => hello )
// 正向后行断言 (?<=) // 匹配前面是"hello"的"world" $pattern = '/(?<=hello)world/'; $string = 'helloworld hellothere world'; preg_match_all($pattern, $string, $matches); echo "\n正向后行断言匹配结果: "; print_r($matches[0]); // 输出: Array ( [0] => world )
// 负向后行断言 (? world )
?>
7.2 使用条件模式
7.3 使用递归模式
7.4 使用注释和模式修饰符
7.5 使用回调函数进行替换
7.6 多行匹配与处理
第一行\n第二行
“;
$pattern = ‘/
if (preg_match($pattern, $html, $matches)) {
echo “\n匹配多行HTML:\n” . $matches[0] . “\n”;
}
?>
8. 性能优化与最佳实践
8.1 避免回溯
]+>/’;
// 高效的正则表达式(使用原子组避免回溯)
$efficientPattern = ‘/<(?>[^>]+)>/’;
$html = ‘
‘;
// 测试低效模式
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
preg_match($inefficientPattern, $html);
}
$inefficientTime = microtime(true) - $start;
// 测试高效模式
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
preg_match($efficientPattern, $html);
}
$efficientTime = microtime(true) - $start;
echo "低效模式执行时间: " . number_format($inefficientTime * 1000, 2) . " 毫秒\n";
echo "高效模式执行时间: " . number_format($efficientTime * 1000, 2) . " 毫秒\n";
?>
8.2 使用具体字符类代替通配符
8.3 预编译正则表达式
8.4 使用合适的函数
8.5 避免过度使用正则表达式
9. 实战案例
9.1 创建一个简单的模板引擎
template = $template;
}
public function render($data) {
// 替换变量 {{variable}}
$result = preg_replace_callback(‘/\{\{(\w+)\}\}/’, function($matches) use ($data) {
$varName = $matches[1];
return isset($data[$varName]) ? $data[$varName] : ”;
}, $this->template);
// 处理条件语句 {% if condition %}…{% endif %}
$result = preg_replace_callback(‘/\{%\s*if\s+(\w+)\s*%\}(.*?)\{%\s*endif\s*%\}/s’, function($matches) use ($data) {
$condition = $matches[1];
$content = $matches[2];
return isset($data[$condition]) && $data[$condition] ? $content : ”;
}, $result);
// 处理循环 {% for item in array %}…{% endfor %}
$result = preg_replace_callback(‘/\{%\s*for\s+(\w+)\s+in\s+(\w+)\s*%\}(.*?)\{%\s*endfor\s*%\}/s’, function($matches) use ($data) {
$itemVar = $matches[1];
$arrayVar = $matches[2];
$content = $matches[3];
if (!isset($data[$arrayVar]) || !is_array($data[$arrayVar])) {
return ”;
}
$result = ”;
foreach ($data[$arrayVar] as $item) {
// 替换循环变量
$itemContent = preg_replace(‘/\{\{‘ . $itemVar . ‘\.(\w+)\}\}/e’, ‘isset($item[\’$1\’]) ? $item[\’$1\’] : \’\”, $content);
$result .= $itemContent;
}
return $result;
}, $result);
return $result;
}
}
// 使用示例
$template = ‘
{{heading}}
{% if showIntro %}
{{introText}}
{% endif %}
产品列表
-
{% for product in products %}
- {{product.name}} – ${{product.price}}
{% endfor %}
‘;
$data = [
‘title’ => ‘产品目录’,
‘heading’ => ‘我们的产品’,
‘showIntro’ => true,
‘introText’ => ‘欢迎查看我们的产品目录!’,
‘products’ => [
[‘name’ => ‘产品A’, ‘price’ => ‘19.99’],
[‘name’ => ‘产品B’, ‘price’ => ‘29.99’],
[‘name’ => ‘产品C’, ‘price’ => ‘39.99’]
],
‘footerText’ => ‘© 2023 我们的公司’
];
$engine = new SimpleTemplateEngine($template);
echo $engine->render($data);
?>
9.2 创建一个路由解析器
routes[] = [
‘method’ => strtoupper($method),
‘pattern’ => $pattern,
‘handler’ => $handler
];
}
public function route($method, $uri) {
$method = strtoupper($method);
foreach ($this->routes as $route) {
if ($route[‘method’] !== $method) {
continue;
}
// 将路由模式转换为正则表达式
$pattern = preg_replace(‘/\{(\w+)\}/’, ‘(?P<$1>[^/]+)’, $route[‘pattern’]);
$pattern = ‘#^’ . $pattern . ‘$#’;
if (preg_match($pattern, $uri, $matches)) {
// 提取命名参数
$params = [];
foreach ($matches as $key => $value) {
if (is_string($key)) {
$params[$key] = $value;
}
}
return [
‘handler’ => $route[‘handler’],
‘params’ => $params
];
}
}
return null; // 没有匹配的路由
}
}
// 使用示例
$router = new SimpleRouter();
// 添加路由
$router->addRoute(‘GET’, ‘/’, ‘HomeController@index’);
$router->addRoute(‘GET’, ‘/users’, ‘UserController@list’);
$router->addRoute(‘GET’, ‘/users/{id}’, ‘UserController@show’);
$router->addRoute(‘POST’, ‘/users’, ‘UserController@create’);
$router->addRoute(‘GET’, ‘/posts/{postId}/comments’, ‘CommentController@listByPost’);
$router->addRoute(‘POST’, ‘/posts/{postId}/comments’, ‘CommentController@create’);
// 测试路由
$testCases = [
[‘method’ => ‘GET’, ‘uri’ => ‘/’],
[‘method’ => ‘GET’, ‘uri’ => ‘/users’],
[‘method’ => ‘GET’, ‘uri’ => ‘/users/123’],
[‘method’ => ‘POST’, ‘uri’ => ‘/users’],
[‘method’ => ‘GET’, ‘uri’ => ‘/posts/456/comments’],
[‘method’ => ‘POST’, ‘uri’ => ‘/posts/789/comments’],
[‘method’ => ‘GET’, ‘uri’ => ‘/nonexistent’]
];
foreach ($testCases as $testCase) {
$result = $router->route($testCase[‘method’], $testCase[‘uri’]);
if ($result) {
echo “路由匹配: ” . $testCase[‘method’] . ” ” . $testCase[‘uri’] . “\n”;
echo “处理器: ” . $result[‘handler’] . “\n”;
if (!empty($result[‘params’])) {
echo “参数:\n”;
foreach ($result[‘params’] as $key => $value) {
echo ” $key: $value\n”;
}
}
} else {
echo “没有找到匹配的路由: ” . $testCase[‘method’] . ” ” . $testCase[‘uri’] . “\n”;
}
echo “\n”;
}
?>
9.3 创建一个简单的Markdown解析器
$1
‘, $html);
$html = preg_replace(‘/^## (.*$)/m’, ‘
$1
‘, $html);
$html = preg_replace(‘/^### (.*$)/m’, ‘
$1
‘, $html);
// 解析粗体和斜体
$html = preg_replace(‘/\*\*(.*?)\*\*/’, ‘$1‘, $html);
$html = preg_replace(‘/\*(.*?)\*/’, ‘$1‘, $html);
// 解析链接
$html = preg_replace(‘/\[(.*?)\]\((.*?)\)/’, ‘$1‘, $html);
// 解析图片
$html = preg_replace(‘/!\[(.*?)\]\((.*?)\)/’, ‘‘, $html);
// 解析无序列表
$html = preg_replace(‘/^\* (.*$)/m’, ‘
- $1
‘, $html);
$html = preg_replace(‘/(<\/ul>\s*
- )/’, ”, $html);
- $1
// 解析有序列表
$html = preg_replace(‘/^\d+\. (.*$)/m’, ‘
‘, $html);
$html = preg_replace(‘/(<\/ol>\s*
- )/’, ”, $html);
// 解析代码块
$html = preg_replace(‘/“`(.*?)“`/s’, ‘
$1
‘, $html);
// 解析行内代码
$html = preg_replace(‘/`(.*?)`/’, ‘$1‘, $html);
// 解析段落
$html = preg_replace(‘/\n\n/’, ‘
‘, $html);
$html = ‘
‘ . $html . ‘
‘;
// 清理空段落
$html = preg_replace(‘/
<\/p>/’, ”, $html);
return $html;
}
}
// 使用示例
$markdown = ‘# 欢迎使用Markdown
这是一个**简单**的Markdown解析器示例。
## 功能特性
– 支持标题
– 支持*斜体*和**粗体**
– 支持[链接](https://example.com)
– 支持图片:

1. 有序列表项1
2. 有序列表项2
3. 有序列表项3
## 代码示例
这是一个行内代码:`$variable = “value”;`
这是一个代码块:
function helloWorld() {
echo “Hello, World!”;
}
> 这是一个引用块。
希望你喜欢这个简单的Markdown解析器!’;
$parser = new SimpleMarkdownParser();
$html = $parser->parse($markdown);
echo $html;
?>
10. 总结
PHP正则表达式是一种强大的文本处理工具,掌握它可以帮助你更高效地处理各种文本操作和数据验证任务。本文从基础概念开始,逐步介绍了正则表达式的各种元素和技巧,并通过大量实例展示了如何在实际应用中使用正则表达式。
关键要点:
基础元素
:了解正则表达式的基本元素,如字符类、量词、断言等,是构建复杂模式的基础。
数据验证
:正则表达式在表单验证、数据清洗等方面非常有用,可以验证电子邮件、电话号码、URL等格式。
文本处理
:使用正则表达式可以高效地提取、替换和格式化文本内容。
高级技巧
:掌握断言、条件模式、递归模式等高级技巧,可以解决更复杂的文本处理问题。
性能优化
:避免回溯、使用具体字符类、预编译正则表达式等技巧可以提高正则表达式的执行效率。
最佳实践
:在适当的情况下使用正则表达式,避免过度使用,并考虑使用PHP内置函数作为替代方案。
通过不断练习和实践,你将能够熟练掌握PHP正则表达式,并在实际项目中灵活应用它们来解决各种文本处理和数据验证问题。