本文實(shí)例講述了PHP正則表達(dá)式處理函數(shù)。分享給大家供大家參考,具體如下:
有時(shí)候在一些特定的業(yè)務(wù)場景中需要匹配,或者提取一些關(guān)鍵的信息,例如匹配網(wǎng)頁中的一些鏈接,
提取一些數(shù)據(jù)時(shí),可能會(huì)用到正則匹配。
下面介紹一下php中的一些常用的正則處理函數(shù)。
一、preg_replace($pattern,$replacement,$subject)
執(zhí)行一個(gè)正則表達(dá)式的搜索和替換。
<?php echo "<pre>"; $str = "12,34:56;784;35,67:897:65"; //要求將上面的:,;都換成空格 print_r(preg_replace("/[,;:]/"," ",$str));?>輸出
12 34 56 784 35 67 897 65
二、preg_match($pattern,$subject,&$matches)
執(zhí)行匹配正則表達(dá)式
<?php echo "<pre>"; $str = "<a href=/"https://www.baidu.com/">團(tuán)購商品</a>"; //匹配出鏈接地址 preg_match("/<a href=/"(.*?)/">.*?<//a>/",$str,$res); print_r($res);?>輸出
Array
(
[0] => 團(tuán)購商品
[1] => https://www.baidu.com
)
三、preg_match_all($pattern,$subject,&$matches)
執(zhí)行一個(gè)全局正則表達(dá)式匹配
<?php echo "<pre>"; $str=<<<EOF <div> <a href="index.php" rel="external nofollow" >首頁</a> <a href="category.php?id=3" rel="external nofollow" >GSM手機(jī)</a> <a href="category.php?id=4" rel="external nofollow" >雙模手機(jī)</a> <a href="category.php?id=6" rel="external nofollow" >手機(jī)配件</a> </div>EOF; //使用全局正則匹配 preg_match_all("/<a href=/"(.*?)/">(.*?)<//a>/s",$str,$res); print_r($res);?>輸出
Array
(
[0] => Array
(
[0] => 首頁
[1] => GSM手機(jī)
[2] => 雙模手機(jī)
[3] => 手機(jī)配件
)
[1] => Array
(
[0] => index.php
[1] => category.php?id=3
[2] => category.php?id=4
[3] => category.php?id=6
)
[2] => Array
(
[0] => 首頁
[1] => GSM手機(jī)
[2] => 雙模手機(jī)
[3] => 手機(jī)配件
)
)
四、preg_split($pattern,$subject)
通過一個(gè)正則表達(dá)式分隔字符串
<?php echo "<pre>"; $str = "12,34:56;784;35,67:897:65"; //分隔字符串 $arr = preg_split("/[,;:]/",$str); print_r($arr);?>輸出
Array
(
[0] => 12
[1] => 34
[2] => 56
[3] => 784
[4] => 35
[5] => 67
[6] => 897
[7] => 65
)
五、preg_quote($str)
轉(zhuǎn)義正則表達(dá)式字符
正則表達(dá)式特殊字符有:. / + * ? [ ^ ] $ ( ) { } = ! < > : -
<?php echo "<pre>"; echo preg_quote("(abc){10}");//在每個(gè)正則表達(dá)式語法的字符前增加一個(gè)反斜杠?>輸出
/(abc/)/{10/}
六、子存儲(chǔ)
<?php echo "<pre>"; //子存儲(chǔ)使用 $date="[2012-08-09],[2012,09-19],[2011/08,09],[2012/10/09],[2013,08,01]"; //將上面字串中合法的日期匹配出來 preg_match_all("//[[0-9]{4}([/-,//])[0-9]{2}//1[0-9]{2}/]/",$date,$a); print_r($a);?>輸出
Array
(
[0] => Array
(
[0] => [2012-08-09]
[1] => [2012/10/09]
[2] => [2013,08,01]
)
[1] => Array
(
[0] => -
[1] => /
[2] => ,
)
)
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選