php正則表達式之preg_match()用法
來源:程序員人生 發布時間:2013-11-20 13:49:01 閱讀次數:2951次
利用 preg_match(),我們可以完成字符串的規則匹配。如果找到一個匹配,preg_match() 函數返回 1,否則返回 0。還有一個可選的第三參數可以讓你把匹配的部分存在一個數組中。在驗證數據時這個功能可以變得非常有用。
實例代碼如下:
- <?php
-
- if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
- print "A match was found.";
- } else {
- print "A match was not found.";
- }
- ?>
取得當前時間
實例代碼如下:
- <?php
-
- $content = "現在時刻:".date("Y-m-d h:i a");
-
- if (preg_match ("/d{4}-d{2}-d{2} d{2}:d{2} [ap]m/", $content, $m))
- {
- echo "匹配的時間是:" .$m[0]. "n";
- }
-
- if (preg_match ("/([d-]{10}) ([d:]{5} [ap]m)/", $content, $m))
- {
- echo "當前日期是:" .$m[1]. "n";
- echo "當前時間是:" .$m[2]. "n";
- }
- ?>
這個例子將驗證出此 Email 地址為正確格式。現在讓我們來看看這段正則表達式所代表的各種規則。
獲取Google首頁title
比如說要獲取google首頁的title內容,代碼如下:
實例代碼如下:
- <?php
- $str = file_get_contents('http://www.google.com');
- preg_match('/<title>(.*)</title>/', $str, $arr);
- echo $arr[1];
- ?>
從網址獲取域名
實例代碼如下:
- <?php
- preg_match("/^(http://)?([^/]+)/i", "http://www.111cn.net/index.html", $matches);
- $host = $matches[2];
- preg_match("/[^./]+.[^./]+$/", $host, $matches);
- echo "domain name is: {$matches[0]}n";
- ?>
preg_match($pattern,$string,$matcher)其中$pattern對應的就是/^(http://)?([^/]+)/i,$string 是http://www.php.net/index.html,$match是匹配到的結果。
如果提供了 matches,則其會被搜索的結果所填充。$matches[0] 將包含與整個模式匹配的文本,$matches[1] 將包
含與第一個捕獲的括號中的子模式所匹配的文本,以此類推。
$matches[0] 將包含與整個模式匹配的文本。咱們用pring_r打印出來第一個$matches:
實例代碼如下:
- Array (
- [0] => http:
- [1] => http:
- [2] => http:
$matches[0] 將包含與整個模式匹配的文本,$matches[1] 將包含與第一個捕獲的括號中的子模式所匹配的文本。在正則中,()代表模式:匹配 pattern 并獲取這一匹配。所獲取的匹配可以從產生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中則使用 $0…$9 屬性。就是說數組中下標為1的值就是正則中/^(http://)?([^/]+)/i第一個()里的值!數組下標2的值以此類推。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈