在php中preg_match()函數是用來執行正則表達式的一個常用的函數,下面我來給大家詳細介紹preg_match使用方法.
函數用法:int preg_match_all ( string pattern, string subject, array matches [, int flags] )
例1,代碼如下:
- <?php
- preg_match_all ("|<[^>]+>(.*)</[^>]+>|U","<b>example: </b><div align=left>this is a test</div>",$out, PREG_SET_ORDER);
- print $out[0][0].", ".$out[0][1]."n";
- print $out[1][0].", ".$out[1][1]."n";
- ?>
- //本例將輸出:
- <b>example: </b>, example:
- <div align=left>this is a test</div>, this is a test
例2,URL 中取出域名,代碼如下:
- <?php
- // 從 URL 中取得主機名
- preg_match("/^(http://)?([^/]+)/i", "http://www.companysz.com/index.html", $matches);
- $host = $matches[2];
- // 從主機名中取得后面兩段
- preg_match("/[^./]+.[^./]+$/", $host, $matches);
- echo "domain name is: {$matches[0]}n";
- ?>
- //本例將輸出:
- domain name is: Vevb.com
preg_match字符串長度問題
preg_match正則提取目標內容,死活有問題,代碼測得死去活來.
后來懷疑PHP 的preg_match有字符串長度限制,果然,發現“pcre.backtrack_limit ”的值默認只設了100000.
解決辦法,代碼如下:
ini_set('pcre.backtrack_limit',999999999);
注:這個參數在php 5.2.0版本之后可用.
另外說說關于:pcre.recursion_limit
pcre.recursion_limit是PCRE的遞歸限制,這個項如果設很大的值,會消耗所有進程的可用堆棧,最后導致PHP崩潰.
也可以通過修改配置來限制,代碼如下:
ini_set('pcre.recursion_limit', 99999);
實際項目應用中,最好也對內存進行限定設置:ini_set('memory_limit','64M');,這樣就比較穩妥妥嘎.
新聞熱點
疑難解答