Skip to content

Instantly share code, notes, and snippets.

@cam-gists
Created July 9, 2012 06:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cam-gists/3074695 to your computer and use it in GitHub Desktop.
Save cam-gists/3074695 to your computer and use it in GitHub Desktop.
PHP: Regex Validation
<?php
// ref: http://komunitasweb.com/2009/03/10-practical-php-regular-expression-recipes/
// Validate Email
if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) {
echo "Your email is ok.";
} else {
echo "Wrong email address format.";
}
//Validate Username
$username = "user_name12";
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
echo "Your username is ok.";
} else {
echo "Wrong username format.";
}
//Validate US Phone #
$phone = "(021)423-2323";
if (preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phone)) {
echo "Your phone number is ok.";
} else {
echo "Wrong phone number.";
}
//Validate IP addresses
$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.";
}
// Validate Us Postal Codes
$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.";
}
// Validate SSN
$ssn = "333-23-2329";
if (preg_match('/^[\d]{3}-[\d]{2}-[\d]{4}$/',$ssn)) {
echo "Your SSN is ok.";
} else {
echo "Wrong SSN.";
}
// CC Validation
$cc = "378282246310005";
if (preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc)) {
echo "Your credit card number is ok.";
} else {
echo "Wrong credit card number.";
}
// URL validation
$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.";
}
// Return Domain from exact url
$url = "http://komunitasweb.com/index.html";
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
echo $host;
// Highlight word
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", '<span style="background:#5fc9f6">\1</span>', $text);
echo $text;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment