2012年1月17日 星期二

preg_match 正規表示式比對

int preg_match ( string pattern, string subject [, array matches [, int flags]])
本函式以 pattern 的規則來剖析比對字串 subject。比對結果傳回的值放在陣列參數 matches 之中,matches[0]
內容就是原字串 subject、matches[1] 為第一個合乎規則的字串、matches[2] 就是第二個合乎規則的字串,餘類推。
若省略參數 matches,則只是單純地比對,找到則傳回值為 true。
// the "i" after the pattern delimiter indicates a case-insensitive search
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.";
}


認證IP是否正確

function validIP($ip){
    return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
} 

網站實例:
preg_match("/product[0-9]{4}.html/i",$_SERVER['REQUEST_URI']
參考regular expressions

沒有留言: