Home > Software design >  Restriction of '@' in php
Restriction of '@' in php

Time:12-11

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.

CodePudding user response:

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
}

CodePudding user response:

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
}
  •  Tags:  
  • php
  • Related