程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP正則表達式(常用的7個例子)

PHP正則表達式(常用的7個例子)

編輯:關於PHP編程

PHP正則表達式(常用的7個例子)


1、驗證E-mail

用filer_var 比用正則匹配更加好

 

if (filter_var('test+email@ansoncheung', FILTER_VALIDATE_EMAIL)) {
    echo "Your email is ok.";
} else {
    echo "Wrong email address format.";
}

 

2、驗證用戶名(驗證用戶名5-20之間)

 

$username = "user_name12";
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
    echo "Your username is ok.";
} else {
    echo "Wrong username format.";
}

 

3、驗證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.";
}

 

4、驗證郵編

 

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

 

5、驗證域名

 

$url = "http://ansoncheung.tk/";
 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.";
 }

6、從特定URL中提取域名

 

 

$url = "http://ansoncheung.tk/articles";
 preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
 $host = $matches[1];
echo $host;

7、文本中關鍵字高亮顯示

 

 

$text = "Sample sentence from AnsonCheung.tk, regular expression 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", '\1', $text);
echo $text;


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved