preg_match

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_match -- 進行正則表達式符合

說明

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_all() 則相反,會一直搜尋到 subject 的結尾處。若果出錯 preg_match() 返回 FALSE

提示: 若果只想檢視一個字串是否包括在另一個字串中,不要用 preg_match()。可以用 strpos()strstr() 替代,要快得多。

例子 1. 在文字中搜尋「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.";
}
?>

例子 2. 搜尋單詞「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.";
}
?>

例子 3. 從 URL 中取出功能變數名

<?php
// 從 URL 中取得主電腦名
preg_match("/^(http:\/\/)?([^\/]+)/i",
    
"http://www.php.net/index.html"$matches);
$host $matches[2];

// 從主電腦名中取得後面兩段
preg_match("/[^\.\/]+\.[^\.\/]+$/"$host$matches);
echo 
"domain name is: {$matches[0]}\n";
?>

本例將輸出:

domain name is: php.net

參見 preg_match_all()preg_replace()preg_split()