Skip to content

PHP Check Regular Expressions with preg_match()

Share Button
<?php

    //Simple Regex Matching code. 

    /** Regular Expression 
    *   accepts:
    *       - upper & lower case letters from a to z 
    *       - numbers from 0 to 9
    *       - dots(.)
    *       - string length between 1 and 20
    */
    $regex = "/^[a-zA-Z0-9.]{1,20}$/";
    /** String to match */
    $stringToMatch = "linuxGet.co.uk";
    
    /** Create function that will accept 2 arguments */
    function matchRegex($regex, $stringToMatch){
        /** If Expression matches do something... */
        if(preg_match($regex, $stringToMatch)){
            echo "Expression matches...";
        /** If expression doesn't match do something else...*/
        } else {
            echo "Expression DOESN'T MATCH !!!!";
        }
    }

    /** Run function */
    matchRegex($regex, $stringToMatch);

?>

 

Result:

Expression matches…

Share Button