How to validate a string in php so that it contains only letters, numbers, and hyphen (-)
Thank you
How to validate a string in php so that it contains only letters, numbers, and hyphen (-)
Thank you
You can use regular expressions. The preg_match
function returns 1 if the string is valid, zero if it is not valid, and FALSE if an error occurs.
To validate letters with accents, numbers and hyphens:
preg_match('/^[A-Za-z0-9-]+$/u', 'lês-criolês-10');
To validate unaccented letters, numbers and hyphens:
preg_match('/^[A-Za-z0-9-]+$/', 'teste-1-2-3');
$pattern = '~^[[:alnum:]-]+$~u';
$str = 'teste-1';
vr((boolean) preg_match($pattern, $str)); // true
$str = 'teste_2';
vr((boolean) preg_match($pattern, $str)); // false
$str = 'maça';
vr((boolean) preg_match($pattern, $str)); // true
[:alnum:]
is a POSIX class that encompasses [[:alpha:][:digit:]]
.
[:alpha:]
= a-zA-Z [:digit:]
= 0-9 As suggested by the @GuilhermeNascimento , it is important to know what the u
modifier is used for end of REGEX.
By default PHP does not support Unicode by performing a byte (8-bit) search. However some characters are not represented only with 8 bits, such as ç
which is represented by 8 bits for c
+ 8 bits for '
(accent) so your search would return false
, since it would not recognize the next byte in ç
.
When using the u
modifier you are activating a search per character and not byte, note that this does not mean that it will be considered 2 bytes but "full character".
See conversion of some characters with this tool , such as ♫
, which is a 3-byte character.
You can do this:
return preg_match('/^[a-zA-Z0-9-]+$/', $string) ? true : false