Search code examples
phpvalidationemailutf-8preg-match

preg_match doesn't work in .php file with UTF-8 encoding


Can somebody explain me how it works?After half hour of thinking what can cause problems with PHP function preg_match I found that file encoding is source of my worries.Giving You example from website:

function  checkEmail($email) {
if (!preg_match("/^( [a-zA-Z0-9] )+( [a-zA-Z0-9\._-] )*@( [a-zA-Z0-9_-] )+( [a-zA-Z0-9\._-] +)+$/" , $email)) {
return false;
}
return true;
};

Function presented above is correct in 100%.I pasted it into my file to just check if my function is wrong but my function and that one above both don't work when UTF-8 enabled and work properly when ANSI enabled.Can You exactly explain where problem is or what mistake I'm doing.Thank You.


Solution

  • You need to tell it the search subject is UTF8.

    function  checkEmail($email) {
        if (!preg_match("/^( [a-zA-Z0-9] )+( [a-zA-Z0-9\._-] )*@( [a-zA-Z0-9_-] )+( [a-zA-Z0-9\._-] +)+$/u" , $email)) {
              return false;
        }
              return true;
    }
    

    In that regex I added the u at the end which makes the pattern and the string utf8.

    Pattern and subject strings are treated as UTF-8.

    -Full documentation (and other modifiers)