regex nif PHP code example

Example 1: regex php

<?php
// First Verif your regex code with https://regex101.com/
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1

// test email with REGEX
if (!preg_match("/[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z]{2,4}/", $emailAddress)){
    //Email address is invalid.
}

// use filter var to valide Email
if(filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) 
{
     //The email address is valid.
} else{
     //The email address is invalid.
}


?>

Example 2: regex validation of name in php

case 3:
                $rgx = "/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i";
        break;

        case 2:
                //read below
                $rgx = "/[^A-Za-z0-9]+/";
        break;

        case 1:
                //read below
                $rgx = "/[^A-Za-z0-9]+/";
        break;

        case 0:
                //if characters are NOT normal
                $rgx = "/[^A-Za-z0-9]+/";
        break;

        default:
                echo "???";
                die("$unit ?");
        break;
}

$n = preg_match($rgx, $unit, $matches);
if ( ($idx == 0) || ($idx == 1) || ($idx == 2) ){
        if ($n) {
                echo "Bad Characters in $unit; Alphanumeric only";
        }
} else {
        if ($n == 0) {
                echo "Incorrect Format in $unit; Enter Valid Info";
        }
}

Tags:

Php Example