php中的PCRE 函數,正則表達式處理函數。
阿新 • • 發佈:2017-11-12
spl 轉義 可能 執行 業務 表達 array 輸出 dex
有時候在一些特定的業務場景中需要匹配,或者提取一些關鍵的信息,例如匹配網頁中的一些鏈接,
提取一些數據時,可能會用到正則匹配。
下面介紹一下php中的一些常用的正則處理函數。
一、preg_replace($pattern,$replacement,$subject)
執行一個正則表達式的搜索和替換。
<?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)
執行匹配正則表達式
<?php echo "<pre>"; $str = "<a href=\"https://www.baidu.com\">團購商品</a>"; //匹配出鏈接地址 preg_match("/<a href=\"(.*?)\">.*?<\/a>/",$str,$res); print_r($res); ?> //輸出 Array ( [0] => 團購商品 [1] => https://www.baidu.com )
三、preg_match_all($pattern,$subject,&$matches)
執行一個全局正則表達式匹配
<?php echo "<pre>"; $str=<<<EOF <div> <a href="index.php">首頁</a> <a href="category.php?id=3">GSM手機</a> <a href="category.php?id=4">雙模手機</a> <a href="category.php?id=6">手機配件</a> </div> EOF; //使用全局正則匹配 preg_match_all("/<a href=\"(.*?)\">(.*?)<\/a>/s",$str,$res); print_r($res); ?> //輸出 Array ( [0] => Array ( [0] => 首頁 [1] => GSM手機 [2] => 雙模手機 [3] => 手機配件 ) [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手機 [2] => 雙模手機 [3] => 手機配件 ) )
四、preg_split($pattern,$subject)
通過一個正則表達式分隔字符串
<?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)
轉義正則表達式字符
正則表達式特殊字符有:. \ + * ? [ ^ ] $ ( ) { } = ! < > : -
<?php echo "<pre>"; echo preg_quote("(abc){10}");//在每個正則表達式語法的字符前增加一個反斜杠 ?> //輸出 \(abc\)\{10\}
六、子存儲
<?php echo "<pre>"; //子存儲使用 $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] => , ) )
詳細版請參考:https://www.cnblogs.com/yafei236/p/4168290.html
php中的PCRE 函數,正則表達式處理函數。