正則表達式本身就是一種語言,這在其它語言是通用的
正則表達式(regular expression)描述了一種字符串匹配的模式,可以用來檢查一個串是否含有某種子串、將匹配的子串做替換或者從某個串中取出符合某個條件的子串等。
strpos(‘abc’); //精確匹配 只能匹配字符串“abc”
正則表達式 //模糊匹配
在SQL中
Where name=’zhangsan’; //精確匹配
Where name like ‘zhang%’; //姓名以zhang開始的字符串
爲什麼使用(使用場景)
1)驗證郵箱 [email protected] [email protected] [email protected]
2)手機號 17002810530 15888888888 18777777777
3)銀行卡號
4)採集器
5)中獎信息 138****8888
6)屏蔽特殊詞彙
入門
<?php$str = 'when I am 8 years old, wo shi yige hao haizi.';
//使用正則判斷是否含有8
$rst = preg_match('/am 8/', $str);
var_dump($rst);
//使用正則判斷是否含有數字
$rst = preg_match('/\d/', $str);
var_dump($rst);
//使用正則判斷是否含有非數字
$rst = preg_match('/\D/', $str);
var_dump($rst);
//取出第一個非數字的字符,放到第三個參數中
preg_match('/\D/', $str, $matches);
//preg_match_all('/\D/', $str, $matches);
var_dump($matches);
echo preg_replace('/\d/', 'number', $str); //將所有的數字替換成number
常用的函數
preg_match()
preg_match_all()
preg_replace()