$string = "Welcome to plus2net.com";
var_dump(filter_var($string, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^W(.*)/"))))
Output is
string(23) "Welcome to plus2net.com"
By using FILTER_VALIDATE_REGEXP we can validate Regular expression .
$string="ZWelcome to plus2net.com";
Output is now
bool(false)
$string = "Welcome to plus2net.com"; // change the first char and see the result
if(filter_var($string, FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=>"/^W(.*)/")))){
echo "yes Cleared ";
}else{
echo " No not cleared ";
}
Output is here
yes Cleared
Although PHP has FILTER_VALIDATE_EMAIL, sometimes custom validation is needed. This example validates an email using a regular expression:
$email = "test@example.com";
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
if (filter_var($email, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => $pattern)))) {
echo "Valid Email";
} else {
echo "Invalid Email";
}
We can use a regex to ensure a password contains at least one uppercase letter, one lowercase letter, one digit, and is at least 8 characters long.
$password = "Password123";
$pattern = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/";
if (filter_var($password, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => $pattern)))) {
echo "Password is strong.";
} else {
echo "Password is weak.";
}
This example validates URLs ( php has FILTER_VALIDATE_URL) that are specific to a certain domain, like *.com domains:
$url = "https://www.example.com";
$pattern = "/^https?:\/\/(www\.)?([a-z0-9]+)\.com$/i";
if (filter_var($url, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => $pattern)))) {
echo "Valid URL";
} else {
echo "Invalid URL";
}