I've this PHP regular expression:
$username = preg_replace('/[^a-z0-9]/i', '', $username);
It allows only A-Z
and 0-9
. How can I allow .
, -
and _
as well?
I've this PHP regular expression:
$username = preg_replace('/[^a-z0-9]/i', '', $username);
It allows only A-Z
and 0-9
. How can I allow .
, -
and _
as well?
$username = preg_replace('/[^a-z0-9._-]/i', '', $username);
Removes anything that isn't ([^]
) one of the characters on the group. Note the hypern is the last one there, so it loses its special meaning.
If you know exactly what you need to match, just specify it in a character group. The dash either needs to be at the very start or very end.
/[A-Z0-9._-]/
$username = preg_replace('/[^a-z0-9._-]/i', '', $username);
Your current code actually does allow both A-Z
and a-z
- the i
flag marks your regular expression as case-insensitive.
You can use the following regex:
/[^a-z0-9._-]/i
/[^a-zA-Z0-9._-]/
/[^a-z0-9.\-_]/
where we are
escaping the hyphenTry
$username = preg_replace('/[^a-z0-9.-_]/i', '', $username);
Easy, just add those characters to the regular expression as well
$username = preg_replace('/[^a-zA-Z0-9._-]/','',$username)
The . needs to be escaped because its the 'matchall' character, the - goes in the end because otherwise it would be used to define a range (we could ofcourse have just escaped it).