Search code examples
phppreg-match

Disabling some characters with preg_match


I'm having an issue with my register page, i noticed that people can register with alt codes like this "ªµµª" and i tried to fix it by using preg_replace but when i did that i couldn't register anymore, atleast not with the worldwide alphabet

    final public function validName($username)  
{
    if(strlen($username) <= 25 && ctype_alnum($username))   
    {           
        return true;        
    }               

    return false;   
}       

Tried to fix it by replacing it with this

if(strlen($username) <= 25 && preg_match("/[^a-zA-Z0-9]+/", $username))

But i'm obviously doing something wrong...


Solution

  • Apparently, you are confusing two different uses of the caret (^) metacharacter.

    Indeed, it may be two things in a regular expression:

    • It may assert the start of the subject, which is what you probably want.
    • It may negate the class, which is what you're doing in your code.

    Source: http://php.net/manual/en/regexp.reference.meta.php

    Here is a modified version of your code, with the caret (^) and dollar ($) signs to assert the start and the end of the strings you're analyzing:

    function validName($username)  
    {
        if (strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username))   
        {           
            return true;        
        }               
    
        return false;   
    }     
    
    $names = array(
      'Abc1',
      'Abc$',
      "ªµµª"
    );
    
    foreach ($names as $name) {
      echo "<br>" . $name . ': ' . (validName($name) ? 'valid' : 'invalid');
    }
    
    // -- Returns: 
    // Abc1: valid
    // Abc$: invalid
    // ªµµª: invalid
    

    Note that you may reduce the code inside your function to one line:

    function validName($username)  
    {
        return strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username);
    }