說明
int preg_match( string pattern, string subject [, array matches [, int flags]] )
在 subject 字元串中搜尋與 pattern給出的正則表達式相匹配的內容。
如果提供了 matches,則其會被搜尋的結果所填充。$matches[0] 將包含與整個模式匹配的文本, $matches[1] 將包含與第一個捕獲的括弧中的子模式所匹配的文本,以此類推。
flags 可以是下列標記:
PREG_OFFSET_CAPTURE如果設定本標記,對每個出現的匹配結果也同時返回其附屬的字元串偏移量。注意這改變了返回的數組的值,使其中的每個單元也是一個數組,其中第一項為匹配字元串,第二項為其偏移量。本標記自PHP 4.3.0 起可用。
flags 參數來自 PHP 4.3.0 起可用。
preg_match() 返回 pattern 所匹配的次數。要么是 0 次(沒有匹配)或 1 次,因為 preg_match() 在第一次匹配之後將停止搜尋。如果出錯 preg_match() 返回FALSE。
注釋
如果你僅僅想要檢查一個字元串是否包含另外一個字元串, 不要使用preg_match()。 使用strpos()或strstr()替代完成工作會更快。
範例
從 URL 中取出域名
<?php // 從 URL 中取得主機名 preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.***.net/index.html", $matches); $host = $matches[2]; // 從主機名中取得後面兩段 preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches); echo "domain name is: {$matches[0]}\n"; ?> |
本例將輸出:
domain name is: PPP.NET |
搜尋單詞“web”
<?php
/* 模式中的 \b 表示單詞的邊界,因此只有獨立的 "web" 單詞會被匹配,
* 而不會匹配例如 "webbing" 或 "cobweb" 中的一部分 */
if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
?>
在文本中搜尋“php”
<?php
// 模式定界符後面的 "i" 表示不區分大小寫字母的搜尋
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
require('/libs/Smarty.class.php');
$smarty = new Smarty;
//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;
$smarty->assign("Name","Fred Irving Johnathan Bradley Peppergill",true);
$smarty->assign("FirstName",array("John","Mary","James","Henry"));
$smarty->assign("LastName",array("Doe","Smith","Johnson","Case"));
$smarty->assign("Class",array(array("A","B","C","D"), array("E", "F", "G", "H"),
array("I", "J", "K", "L"), array("M", "N", "O", "P")));
$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));
$smarty->assign("option_values", array("NY","NE","KS","IA","OK","TX"));
$smarty->assign("option_output", array("New York","Nebraska","Kansas","Iowa","Oklahoma","Texas"));
$smarty->assign("option_selected", "NE");
$smarty->display('index.tpl');
?>
取得當前時間
<?php
//需要匹配的字元串。date函式返回當前時間。 "現在時刻:2012-04-20 07:31 am"
$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"; //"2012-04-20 07:31 am"
}
//分別取得日期和時間
if (preg_match ("/([\d-]{10}) ([\d:]{5} [ap]m)/", $content, $m))
{
echo "當前日期是:" .$m[1]. "\n"; //"2012-04-20"
echo "當前時間是:" .$m[2]. "\n"; //"07:31 am"
}
?>