4.2. 使用正则
持之以恒,方得始终!
php中 preg_xxx()
系列的函数,都是可以用到正则的,可以直接查手册使用。
通配符 .
比如 .at
, 可以匹配到 cat, sat, mat, #at…
preg_match('/.at/', '123', $matches);
print_r($matches);
[ ]
[a-z]at 匹配a-z中的一个字符,后面跟at
[aeiou] 匹配aeiou中的任意一个字符
[a-zA-Z] 匹配任意一个字母
[^a-z] 不在a-z中的一个字符
字符集
[[:alnum:]] 字母和数字
[[:alpha:]] 字母
[[:lower:]] 小写字母
[[:upper:]] 大写字母
[[:digit:]] 数字
[[:xdigit:]] 十六进制数字
[[:punct:]] 标点符号
[[:blank:]] 制表符,空格
[[:space:]] 空白字符
*, +
*
前面的内容重复0次,或更多次。+
前面的内容重复1次,或更多次。
[[:alnum:]]+ 至少有一个字母或数字
preg_match('/[[:alnum:]]+/', '_1a', $matches);
()
(very)*large
very作为一个整体匹配,可出现0次h或多次。
可以匹配到 large, very large, very very large
preg_match('/(very)*large/', 'aaalarge', $matches);
print_r($matches);
/* Array
(
[0] => large
) */
{ }
{3}
重复3次{2,4}
重复2~4次{2, }
至少2次
(very){1,3}
表示匹配 very, veryvery, veryveryvery
^ , $
^
子字符串必须出现在被搜索字符串的开始处。$
子字符串必须出现在被搜索字符串的末尾。
// ^bob 匹配开始处是否有bob字符串
preg_match('/^bob/', 'aaalabob', $matches);
print_r($matches);
/* Array
(
) */
// com$ com是否在末尾有出现
preg_match('/com$/', 'aaalabobcom', $matches);
print_r($matches);
/* Array
(
[0] => com
) */
// ^[a-z]$ 表示只匹配一个包含在a-z中的单个字符
preg_match('/^[a-z]$/', 'ab', $matches);
print_r($matches);
/* Array
(
) */
|
com|edu|net
, 表示匹配 com或edu或net
匹配特殊字符
比如 , . 、{ ¥ \
,我们可以在其前面加一个转义符\
。
一些特殊字符在[ ]
外面的含义:
\ 转义字符
^ 在字符串开始处匹配
$ 在字符串末尾匹配
. 通配符,匹配除换行符 \n 之外的字符
| 或选择
( 子模式的开始
) 子模式的结束
* 重复0次或更多
+ 重复1次或更多
{ } 指定重复次数
? 标记一个子模式为可选的
一些特殊字符在 [ ]
里面的含义:
\ 转义字符
^ 非,仅用在开始位置
- 用于指明字符范围
下单订单中的应用
比如之前的,我们在反馈文本中匹配 shop, customer service, retail 需要做三次搜索,如果用正则,一次即可。shop|customer service|retail
我们还可以验证电子邮件地址^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$
我们分段来看^[a-zA-Z0-9_\-.]+
至少要有一个这里面的字符,以这个开头@
匹配@[a-zA-Z0-9\-]+
至少匹配一个里面的字符\.
匹配 . 方括号外面,要用转义,否则可能是通配符了。[a-zA-Z0-9\-.]+$
至少匹配这里面的一个字符结尾。
使用正则查找子字符串
$email = "11@qq.com";
preg_match('/^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/', $email, $matches);
if(!empty($matches)) {
echo "yes";
} else {
echo "not a invalid email";
}
$feedback = "hello, is good, shop, bye";
preg_match('/shop|customer service|retail/', $feedback, $matches);
if(!empty($matches)) {
echo "yes";
} else {
echo "not";
}
使用正则替换字符串
$feedback = "hello, is good, shop, bye";
$newfeedback = preg_replace('/shop/', 'day', $feedback);
echo $newfeedback; // hello, is good, day, bye
使用正则分割字符串
$address = "username@example.com";
$arr = preg_split('/(\.|@)/', $address);
print_r($arr);
/* Array
(
[0] => username
[1] => example
[2] => com
) */
改变一下参数,再看另外一种结果
$address = "username@example.com";
$arr = preg_split('/(\.|@)/', $address, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($arr);
/* Array
(
[0] => username
[1] => @
[2] => example
[3] => .
[4] => com
) */
如有任何侵权行为,请通知我删除,谢谢大家!
个人邮箱:865460609@qq.com