利用 preg_match(),我們可以完成字符串的規(guī)則匹配。如果找到一個(gè)匹配,preg_match() 函數(shù)返回 1,否則返回 0。還有一個(gè)可選的第三參數(shù)可以讓你把匹配的部分存在一個(gè)數(shù)組中。在驗(yàn)證數(shù)據(jù)時(shí)這個(gè)功能可以變得非常有用。
實(shí)例代碼如下:
- <?php
- // 模式定界符后面的 "i" 表示不區(qū)分大小寫字母的搜索
- 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.";
- }
- ?>
取得當(dāng)前時(shí)間
實(shí)例代碼如下:
- <?php
- //需要匹配的字符串。date函數(shù)返回當(dāng)前時(shí)間。 "現(xiàn)在時(shí)刻:2012-04-20 07:31 am"
- $content = "現(xiàn)在時(shí)刻:".date("Y-m-d h:i a");
- //匹配日期和時(shí)間.
- if (preg_match ("/d{4}-d{2}-d{2} d{2}:d{2} [ap]m/", $content, $m))
- {
- echo "匹配的時(shí)間是:" .$m[0]. "n"; //"2012-04-20 07:31 am"
- }
- //分別取得日期和時(shí)間
- if (preg_match ("/([d-]{10}) ([d:]{5} [ap]m)/", $content, $m))
- {
- echo "當(dāng)前日期是:" .$m[1]. "n"; //"2012-04-20"
- echo "當(dāng)前時(shí)間是:" .$m[2]. "n"; //"07:31 am"
- }
- ?>
這個(gè)例子將驗(yàn)證出此 Email 地址為正確格式。現(xiàn)在讓我們來看看這段正則表達(dá)式所代表的各種規(guī)則。
獲取Google首頁title
比如說要獲取google首頁的title內(nèi)容,代碼如下:
實(shí)例代碼如下:
- <?php
- $str = file_get_contents('http://www.google.com');
- preg_match('/<title>(.*)</title>/', $str, $arr);
- echo $arr[1];
- ?>
從網(wǎng)址獲取域名
實(shí)例代碼如下:
- <?php
- preg_match("/^(http://)?([^/]+)/i", "http://www.111cn.net/index.html", $matches);
- $host = $matches[2]; // 從主機(jī)名中取得后面兩段
- preg_match("/[^./]+.[^./]+$/", $host, $matches);
- echo "domain name is: {$matches[0]}n";
- ?>
preg_match($pattern,$string,$matcher)其中$pattern對應(yīng)的就是/^(http://)?([^/]+)/i,$string 是http://www.php.net/index.html,$match是匹配到的結(jié)果。
如果提供了 matches,則其會被搜索的結(jié)果所填充。$matches[0] 將包含與整個(gè)模式匹配的文本,$matches[1] 將包
含與第一個(gè)捕獲的括號中的子模式所匹配的文本,以此類推。
$matches[0] 將包含與整個(gè)模式匹配的文本。咱們用pring_r打印出來第一個(gè)$matches:
實(shí)例代碼如下:
- Array (
- [0] => http://www.111cn.net
- [1] => http://
- [2] => http://www.companysz.com )
$matches[0] 將包含與整個(gè)模式匹配的文本,$matches[1] 將包含與第一個(gè)捕獲的括號中的子模式所匹配的文本。在正則中,()代表模式:匹配 pattern 并獲取這一匹配。所獲取的匹配可以從產(chǎn)生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中則使用 $0…$9 屬性。就是說數(shù)組中下標(biāo)為1的值就是正則中/^(http://)?([^/]+)/i第一個(gè)()里的值!數(shù)組下標(biāo)2的值以此類推。
新聞熱點(diǎn)
疑難解答