Search code examples
phpstringnullpreg-match

How to preg_match a variable which can be NULL in PHP?


I got a problem with the PHP function preg_match today.

I want to match exact 12 characters in a string ($test='123456789012') OR $test = NULL

My problem is the OR NULL call how is the RegEx for this NULL variable.

Tried: preg_match("/^([\w.-]{12})|(NULL)$/",$test);


Solution

  • A NULL value is not a string literal with the letters NULL, so if you're searching for NULL when something is NULL they will never match.

    You can do

    if($test)
        preg_match("/^([\w.-]{12})$/",$test);
    else
        //whatever works