本文實例講述了PHP正則表達式處理函數(shù)。分享給大家供大家參考,具體如下:
有時候在一些特定的業(yè)務場景中需要匹配,或者提取一些關鍵的信息,例如匹配網(wǎng)頁中的一些鏈接,
提取一些數(shù)據(jù)時,可能會用到正則匹配。
下面介紹一下php中的一些常用的正則處理函數(shù)。
一、preg_replace($pattern,$replacement,$subject)
執(zhí)行一個正則表達式的搜索和替換。
?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í)行匹配正則表達式
?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)
執(zhí)行一個全局正則表達式匹配
?php
echo "pre>";
$str=EOF
div>
a href="index.php" rel="external nofollow" >首頁/a>
a href="category.php?id=3" rel="external nofollow" >GSM手機/a>
a href="category.php?id=4" rel="external nofollow" >雙模手機/a>
a href="category.php?id=6" rel="external nofollow" >手機配件/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)
轉(zhuǎn)義正則表達式字符
正則表達式特殊字符有:. \ + * ? [ ^ ] $ ( ) { } = ! > : -
?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] => ,
)
)
詳細版請參考://www.jb51.net/article/160947.htm
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php正則表達式用法總結(jié)》、《php程序設計安全教程》、《php安全過濾技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《php字符串(string)用法總結(jié)》及《php+mysql數(shù)據(jù)庫操作入門教程》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- php 正則去掉p> /p> 空格 與p>br/>/p>
- php正則表達式使用方法整理集合
- PHP常用正則表達式精選(推薦)
- PHP正則表達式筆記與實例詳解
- PHP中PCRE正則解析代碼詳解
- PHP正則判斷一個變量是否為正整數(shù)的方法
- PHP正則驗證字符串是否為數(shù)字的兩種方法并附常用正則
- PHP正則匹配到2個字符串之間的內(nèi)容方法
- PHP正則解析多重循環(huán)模板示例
- PHP正則過濾處理微信昵稱中emoji字符的方法
- PHP實現(xiàn)正則匹配所有括號中的內(nèi)容
- PHP使用正則表達式實現(xiàn)過濾非法字符串功能示例
- PHP簡單實現(xiàn)正則匹配省市區(qū)的方法
- PHP實現(xiàn)正則表達式分組捕獲操作示例
- phpstorm 正則匹配刪除空行、注釋行(替換注釋行為空行)
- PHP利用正則表達式實現(xiàn)手機號碼中間4位用星號(*)替換顯示功能
- 史上最全的PHP正則表達式(手機號需要加上177-***)
- PHP正則之正向預查與反向預查講解與實例