Allow only letters, numbers and hyphen

1

How to validate a string in php so that it contains only letters, numbers, and hyphen (-)

Thank you

    
asked by anonymous 01.04.2016 / 00:22

3 answers

5

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');
    
01.04.2016 / 00:52
6

Code

$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

Explanation

[:alnum:] is a POSIX class that encompasses [[:alpha:][:digit:]] .

  • [:alpha:] = a-zA-Z
  • [:digit:] = 0-9

Editing

As suggested by the @GuilhermeNascimento , it is important to know what the u modifier is used for end of REGEX.

Unicode

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.

Related question.
Article related.

    
01.04.2016 / 13:52
1

You can do this:

return preg_match('/^[a-zA-Z0-9-]+$/', $string) ? true : false
    
01.04.2016 / 00:42