正则表达式
正则表达式
测试网址
http://www.rexv.org
1.正则表达式基础语法
完整的正则表达式由两种字符组成 特殊字符(元字符) 普通字符(文本)
/^\d+hello.*/
^ \d + . *都是元字符
hello是文本字符
2.常见元字符列表
.
\w
\s
\d
\b
^
$
\xxx
\xdd
\uxxx
3.[-0-9A-Z.?] 元字符有哪些
. ? 不是元字符 []优先级更高
4.字符转义
test.php 匹配 test.php
5.$
单引号会转义转义符
测试:
333333$33\33333
要匹配上面字符串中的 "$" 正则怎么写
在PHP中用pre_match函数分别用单引号 双引号匹配上面的$
表示式需要的规则 \$
双引号 解析字符
单引号 只会解析反斜杠的转义字符
单引号表示上面的字符串 \\$ (四个字符中只有两个转义需要解析)
双引号表示上面的字符串 \\\$ (四个字符都解析都需要转义)
<?php
$uids = '333333\$33\33333';
$uids2 = '333333\$33\33333';
$uids = preg_match_all("/\\\\\\\$/",$uids,$matchs);
$uids2 = preg_match_all('/\\\\\$/',$uids2,$matchs2);
print_r($matchs);
print_r("<br/>");
print_r($matchs2);
?>
6.多选结构
Windows98|Windows2000|WindosXP 以W98 或者 W2000 或者 WXP
^Windows98|Windows2000|WindosXP$ 以W98开头 或者 包含Windows2000
或者 以WindowsXP结尾 都在或的范围内
结尾
Windows(98|2000|XP) W98 或者 W2000 或者 WXP
多选结构可以包括很多字符 但是不能超越括号
开头结尾或者小括号
7.分组与向后引用
8.环视(零宽断言)
实例:
(?=jeffrey)jeff 匹配jeffrey单词中的jeff
jeff(?=rey) 匹配jeffrey单词中的jeff
环视为数值添加逗号
5345678986 5345,678,986
每三位加逗号
分析:
需要找到一个位置 将位置替换为 ',' 这个位置符合以下条件
1.左边必须有数字
2.右边的的数字是3的个数
实例:
$string = '5345678986';
$pattern = '/(?<=\d)(?=(\d{3})+$)/';
$replacement = ',';
print_r(preg_replace($pattern,$replacement,$string));
9.贪婪非贪婪(匹配优先和忽略优先)
a.b aabab 匹配整个长度
a.?b aabab 匹配整个aab ab
10.正则的引擎
DFA NFA引擎分类
11.回溯
12.表达式优化
- .与(?:.)在逻辑上相等 前者速度更快 引擎做了内部优化
- 尽量使用非捕获的括号
- 消除不必要的字符组 [.]与.逻辑上相等 后者更快
- 字符组优于多选结构 [abc]优于多选结构
- 忽略有限还是匹配优先
13.PHP模式修饰符
i 大小写不敏感匹配
m 增强的行锚点模式
x 空白和#注释将被忽略
s 点号元字符匹配所有字符 包含换行符
e 将替换后的字符串作为php代码评估执行
PCRE分隔符号
/xaxsa/
asdas#
都可以
相关文章
- [PHP] laravel中的api路由前缀
- [PHP] 服务容器绑定接口测试
- [mysql] join查询没有走索引的原因
- [mysql] left join 和 join 和right join的区别
- [PHP] 理解依赖注入容器-自动注入
- [PHP] 理解依赖注入容器
- [PHP] ::class的具体作用
- [PHP] composer install和composer update的区别
- [PHP] 解决composer install报错: it could not be found in any version, there may be a typo in the package name
- [PHP] 对象和引用
- [HTTP] post传递数据的两种content-type application/x-www-form-urlencoded multipart/form-data
- [Nginx]使用ngx_http_image_filter_module实现压缩图片为缩略图
- [tcp] 服务端大量close_wait 和 time_wait状态
- [nginx] nginx的变量拼接与if判断
- [nginx] nginx的常用内置变量
- [PHP] 发布一个类库到composer
- [PHP] 重要操作手机短信验证逻辑梳理
- [css] position:fixed居中问题
- [PHP] xml转对象函数simplexml_load_string
- [MySQL] 理解MySQL索引合并index_merge