skip to Main Content

Problem in restricting "@" in username of signup form.
I am creating a website where i want to know how to restrict "@" in php.
I tried preg replace

preg_replace('/@/', '@', $username);

but it is not working. What is the appropriate ‘preg_replace’ value to restrict ‘@’ in php.

2

Answers


  1. You can use str_replace preg_replace to remove all ocurrencies of the @ symbol

    All of these are essentially equivalent.

    $username = str_replace('@','',$username);
    $username = preg_replace('/@/','',$username);
    $username = preg_replace('/[^@']/', '', $username); 
    

    The last one can take a list of restricted characters within the square brackets

    If you want to just check for an @ symbol, I would use strpos instead

    if(strpos($username, '@') !== false){
      // do something
    }
    
    Login or Signup to reply.
  2. To check the presence of a substring, you can use str_contains

    $username = $_POST['username']; //or whatever source
    if (str_contains($username, '@')) {
        throw new Exception('Username cant contain @'); //or whatever expected behavior
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search