PHP Regular Expressions (7 common examples)
1. Verify e-mail
It's better to use filer_var than regular match.
if (Filter_var (' Test+email@ansoncheung ', Filter_validate_email)) { echo "Your email is ok.";} else { echo "wrong Email address format. ";}
2. Verify user name (verify user name 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. Verify IP Address
$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. Verification ZIP Code
$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. Verify the domain name
$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. Extracting domain names from specific URLs
$url = "Http://ansoncheung.tk/articles"; Preg_match (' @^ (?:/HTTP//)? ( [^/]+) @i ', $url, $matches); $host = $matches [1];echo $host;
7. Keyword highlighting in text
$text = "Sample sentence from ansoncheung.tk, regular expression had 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 Regexe N) is written in a formal language the can is interpreted by a regular expression processor "; $text = Preg_replace ("/\b (R Egex) \b/i ", '\1', $text); Echo $text;
http://www.bkjia.com/PHPjc/987986.html www.bkjia.com true http://www.bkjia.com/PHPjc/987986.html techarticle PHP Regular Expressions (Common 7 examples) 1, verify e-mail with Filer_var than with regular match better if (Filter_var (Test+email@ansoncheung, Filter_validate_email)) {echo Your email i ...