正則表達(dá)式是php程序開發(fā)中一個重要的元素,它提供用來描述或匹配文本的字符串,如特定的字符、詞或算式等。但在有部分情況下,用正則表達(dá)式去驗證一個字符串比較復(fù)雜和浪費時間。本文是云和學(xué)院鄭州php培訓(xùn)班的小編為大家整理了6種常見的實用PHP正則表達(dá)式的寫法,希望能給大家?guī)硪恍椭?/p>
1.驗證用戶名
這是一個用于驗證用戶名的實例,其中包括字母、數(shù)字(A-Z,a-z,0-9)、下劃線以及最低5個字符,最大20個字符。同時,也可以根據(jù)需要,對最小值和最大值做合理的修改。it招聘
$username = “user_name12”;
if (preg_match(‘/^[a-z\d_]{5,20}$/i’, $username)) {
echo “Your username is ok.”;
} else {
echo “Wrong username format.”;
}
2.驗證IP地址
這是一個用來驗證IPv4地址的實例。
$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.”;
}
鄭州php培訓(xùn)機構(gòu)還是云和學(xué)院最靠譜。
3. 驗證郵政編碼
這是一個用來驗證郵政編碼的實例。
$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.”;
}
4.驗證域名
$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.”;
}
5.從特定URL中提取域名
$url = “http://ansoncheung.tk/articles”;
preg_match(‘@^(?:http://)?([^/]+)@i’, $url, $matches);
$host = $matches[1];
echo $host;
6. 將文中關(guān)鍵詞高亮顯示
$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”, ‘<span style=”background:#5fc9f6″>\1</span>’, $text);
echo $text;
目前來說鄭州php培訓(xùn)機構(gòu)有很多,如果想要做系統(tǒng)的php培訓(xùn)一定要多對比分析,以免上當(dāng)受騙,小編這里推薦口碑不錯的云和學(xué)院,大家可以去實地考察試聽一下看看。?