<?php // パターンのデリミタの後の "i" は、大小文字を区別しない検索を示す if (preg_match("/php/i", "PHP is the web scripting language of choice.")) { echo "A match was found."; } else { echo "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.")) { echo "A match was found."; } else { echo "A match was not found."; }
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) { echo "A match was found."; } else { echo "A match was not found."; } ?>
例 3. URL からドメイン名を得る
<?php // get host name from URL preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.php.net/index.html", $matches); $host = $matches[2];
// get last two segments of host name preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches); echo "domain name is: {$matches[0]}\n"; ?>