PHP preg_match實現(xiàn)正則表達式匹配功能【輸出是否匹配及匹配值】
本文實例講述了PHP preg_match實現(xiàn)正則表達式匹配功能。分享給大家供大家參考,具體如下:
preg_match — 執(zhí)行一個正則表達式匹配
preg_match ( $pattern , $subject , $matches )
搜索subject與pattern給定的正則表達式的一個匹配.
參數(shù) :
pattern : 要搜索的模式,字符串類型(正則表達式)。
subject : 輸入的字符串。
matches :(可有可無)如果提供了參數(shù)matches,它將被填充為搜索結(jié)果。 $matches[0]將包含完整模式匹配到的文本, $matches[1] 將包含第一個捕獲子組匹配到的文本,以此類推。
返回值 :
preg_match()返回 pattern 的匹配次數(shù)。 它的值將是0次(不匹配)或1次,因為preg_match()在第一次匹配后 將會停止搜索。preg_match_all()不同于此,它會一直搜索subject 直到到達結(jié)尾。 如果發(fā)生錯誤preg_match()返回 FALSE。
實例1:
$label = 'content/112';
$a = preg_match('#content/(\d+)#i', $label, $mc);
var_dump($a);
var_dump($mc);
輸出:
int(1)
array(2) {
[0]=>
string(11) "content/112"
[1]=>
string(3) "112"
}
實例2:
$label = 'content/112';
$a = preg_match('#(\w+)/(\d+)#i', $label, $mc);
var_dump($a);
var_dump($mc);
輸出:
int(1)
array(3) {
[0]=>
string(11) "content/112"
[1]=>
string(7) "content"
[2]=>
string(3) "112"
}
實例3:
$label = 'content/112';
$a = preg_match('#content1111111/(\d+)#i', $label, $mc);
var_dump($a);
var_dump($mc);
輸出:
int(0)
array(0) {
}
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php正則表達式用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
一些PHP Coding Tips(php小技巧)[2011/04/02最后更新]
以下是一些PHP Coding Tips. 當(dāng)然, 這些Tips并不一定僅僅局限于PHP.大家有什么好的心得, 歡迎直接回復(fù)本文與更多的人分享.. 謝謝2011-05-05
PHP 函數(shù)call_user_func和call_user_func_array用法詳解
下面來和大家分享一下這個call_user_func_array和call_user_func函數(shù)的用法,另外附贈func_get_args()函數(shù)和func_num_args()函數(shù),嘿嘿!!2014-03-03

