php - preg_match
任務:匹配一個函數名或者變量名,如果碰到alpha,numeric,_以外的全部不允許通過。
實驗1:
<?php //第一個字符不符合就直接退出正則匹配 $str = '%abcscript%d'; var_dump(preg_match('/^(\w*)$/', $str, $matches)); var_dump($matches); #########output######## #int(0) #array(0) { #} ########################匹配到 $str1 = 'abcscriptd123_'; var_dump(preg_match('/^(\w*?)$/', $str1, $matches)); var_dump($matches); #########output######## #int(1) #array(2) { # [0]=> # string(14) "abcscriptd123_" # [1]=> # string(14) "abcscriptd123_" #} ########################中間有不匹配模式的 $str2 = 'acd%acd'; var_dump(preg_match('/^(\w*?)/', $str2, $matches)); var_dump($matches); #########output######## #int(1) #array(2) { # [0]=> # string(0) "" # [1]=> # string(0) "" #} ##################### //檢查一個字符串里面僅包含字母數字或者下劃線?第一個的結果顯而易見,preg_match返回0,第二個的結果如預期是全串都符合并匹配到,第三個的結果有些出人意料,那為什么preg_match返回1,而$matches未如預期一樣包含匹配到的acd呢?
再做一個實驗,實驗2
<?php #中間有不匹配模式的 $str2 = 'acd%acd'; var_dump(preg_match('/^(\w*)/', $str2, $matches)); var_dump($matches); #########output######## #int(1) #array(2) { # [0]=> # string(3) "acd" # [1]=> # string(3) "acd" #} #####################實驗2的結果:這次可以匹配到符合條件的部分子串 "acd" 了。
對比結果表明:?這個貪婪匹配符起到了很重要的作用,但是對其的工作原理仍然不甚明了。需要繼續深入理解。?
那么如何完成任務?要檢查一個字符串是否只包含alpha, numeric, _
結論是: preg_match('/(\w*)/', $str, $matches);
檢查$matches[1] == $str,如果為true則表示該字符串滿足條件,為false則表示該字符串不滿足條件
<?php $str = 'acd123_'; var_dump(check_word($str)); $str = 'acd%123_'; var_dump(check_word($str)); $str = '%acd123_'; var_dump(check_word($str));function check_word($str) {preg_match('/^(\w*)/', $str, $matches);if($matches[1] == $str){return true;} else {return false;} }輸出:
bool(true) bool(false) bool(false)任務:把ubb中img標簽的內容找出來[img]100.png[/img]
目標:熟悉正則表達式中()的用法
代碼:
<?php$str = '[img]100[/img]test.png[img]1000[/img]'; preg_match_all('/\[img\](.*?)\[\/img\]/', $str, $matches); var_dump($matches);
輸出:
array(2) {[0]=>array(2) {[0]=>string(14) "[img]100[/img]"[1]=>string(15) "[img]1000[/img]"}[1]=>array(2) {[0]=>string(3) "100"[1]=>string(4) "1000"} }任務:把[img]100[/img]提取出來,滿足兩個要求:能夠提取100,并且能夠提取出[img]100[/img]這樣的模式
目標:熟悉正則表達式中()的用法
代碼:
<?php$str = '[img]100[/img]test.png[img]1000[/img]'; preg_match_all('/(\[img\](.*?)\[\/img\])/', $str, $matches); var_dump($matches);?
輸出:?
array(3) {[0]=>array(2) {[0]=>string(14) "[img]100[/img]"[1]=>string(15) "[img]1000[/img]"}[1]=>array(2) {[0]=>string(14) "[img]100[/img]"[1]=>string(15) "[img]1000[/img]"}[2]=>array(2) {[0]=>string(3) "100"[1]=>string(4) "1000"} }理解:正則表達式的括號()能提取字符串中的那些匹配的串,0號match是整個模式的匹配串,1號match是從左往右的第一個()括號中匹配的內容,2號match是第二個()括號中匹配的內容,以此類推。
?
關于preg_match_all, 可見另一篇文章:http://www.cnblogs.com/helww/p/3248345.html
?
keyword: preg_match preg_match_all
轉載于:https://www.cnblogs.com/helww/p/3466720.html
總結
以上是生活随笔為你收集整理的php - preg_match的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dotpeek的导出
- 下一篇: 女子耳朵得“脚气”:游泳导致真菌感染