preg_match_all函數是用來擷取指定資料內容的,它經常用於執行正則表達多,下面我來給大家介紹兩個關於preg_match_all函數實現教程,一個是擷取url參數,一個是擷取內容中圖片方法。
preg_match_all — 執行一個全域Regex匹配
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
例
| 代碼如下 |
複製代碼 |
preg_match_all("|<[^>]+>(.*)]+>|U", "example: this is a test", $out, PREG_PATTERN_ORDER); echo $out[0][0] . ", " . $out[0][1] . "n"; echo $out[1][0] . ", " . $out[1][1] . "n"; ?> |
如何擷取偽靜態url中的參數變數,已經對應的值。
比如說。你現在url的是這樣的。/js/d1b3cid419299191rs好指令碼
你的.htaccess檔案會這樣寫rewirte規則 RewriteRule ^js/(.*)$ /index.php?m=Sell&a=index&g=$1 [QSA,PT,L]
這樣你就可以把g接收過來。
| 代碼如下 |
複製代碼 |
$get = 'd1b3cid419299191rs好指令碼'; $rs_pos = strpos($get,'rs'); if($rs_pos !== false) { $rs = substr($get,$rs_pos); $rs = str_replace('rs','',$rs); $rs = strpos($rs,'/')!==false ? substr($rs,0,strpos($rs,'/')) : $rs; $get = substr($get,0,$rs_pos); } echo 'keywords='.$rs; echo ' '; preg_match_all('/([a-z]*)([0-9]+)/',$get,$m); if($m) { $k = $v = ''; $count = count($m[1]); for($i = 0; $i <= $count; $i++) { ${$m[1][$i]} = $m[2][$i]; if(isset(${$m[1][$i]})) { echo $m[1][$i].'='.${$m[1][$i]}; echo ' '; } } } |
結果:keywords=好指令碼,d=1,b=3,cid=419299191
匹配文章中的圖片
| 代碼如下 |
複製代碼 |
$con = file_get_contents("http://www.bkjia.com/"); $pattern="/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg|.png]))['|"].*?[/]?>/"; preg_match_all($pattern,$con,$match); print_r($match); ?> 輸出代碼 Array ( [0] => Array ( [0] => [1] => [2] => ) [1] => Array ( [0] => http://www.bkjia.com/uploadfile/2013/0905/20130905074915895.png [1] => http://www.bkjia.com/uploadfile/2013/0905/20130905074915639.jpg [2] => http://www.bkjia.com/uploadfile/2013/0905/20130905074915742.jpg ) ) |
http://www.bkjia.com/PHPjc/445630.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/445630.htmlTechArticlepreg_match_all函數是用來擷取指定資料內容的,它經常用於執行正則表達多,下面我來給大家介紹兩個關於preg_match_all函數實現教程,一個是獲...