(PHP 3>= 3.0.9, PHP 4 )
preg_match -- 正規表現検索を行う
説明
int preg_match (string pattern, string subject [, array
matches])
patternで指定した正規表現により
subjectを検索します。
matchesが指定された場合、検索結果が代入されます。
$matches[0]はパターン全体にマッチしたテキストが代入され、
$matches[1]は最初の括弧付きのサブパターンにマッチしたテキスト
が代入され、といったようになります。
文字列subjectにpatternがマッチした場合は
trueを返し、マッチしなかったか、エラーを発生した場合にfalseを
返します。
例 1. 文字列"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"を探す
// パターン内の\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からドメイン名を得る
preg_match("/^(.*)([^\.]+\.[^\.]+)(\/.*)?/U",
"http://www.php.net/index.html", $matches);
// 2番目の括弧内のパターンを表示
echo "domain name is: ".$matches[2]."\n";
|
|
この例の出力は以下となります。
preg_match_all(),
preg_replace(),
preg_split()も参照下さい。