【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" を探す

    /* パターン内の b は単語の境界を示す。このため、独立した単語の
    "web"にのみマッチし、"webbing" や "cobweb" のような単語の一部にはマッチしない */

    if (preg_match("/bwebb/i", "PHP is the web scripting language of choice.")) {
      echo "A match was found.";
    } else {
      echo "A match was not found.";
    }

郵便番号の形式か確認する


    $zipcode = "123-4567";
    if (preg_match("/^([0-9]{3})(-[0-9]{4})?$/i",$zipcode)) {
      echo "Your Zip code is ok.";
    } else {
      echo "Wrong Zip code.";
    }

メールアドレスの形式か確認する


    $email = "test@example.com";
    if (preg_match('/^[^0-9][a-zA-Z0-9_] ([.][a-zA-Z0-9_] )*[@][a-zA-Z0-9_] ([.][a-zA-Z0-9_] )*[.][a-zA-Z]{2,4}$/',$email)) {
      echo "ok.";
    } else {
      echo "Wrong email address format";
    }

IPアドレスの形式か確認する


    $IP = "198.168.1.78";
    if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)) {
      echo "Your IP address is ok.";
    } else {
      echo "Wrong IP address.";
    }

URLの形式か確認する


    $url = "http://komunitasweb.com/";
    if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*) ):?(d )?/?/i', $url)) {
      echo "Your url is ok.";
    } else {
      echo "Wrong url.";
    }

urlからドメインを抽出する


    $url = "http://komunitasweb.com/index.html";
    preg_match('@^(?
    $host = $matches;
    echo $host;

特定の文字を強調する


    $text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
    $text = preg_replace("/b(regex)b/i", 'background:#5fc9f6">1', $text);
    echo $text;