Allow only letters, numbers and hyphen

Asked

Viewed 9,575 times

1

How to validate a php string to contain only letters, numbers and hyphen ( - )

Thank you

3 answers

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 class POSIX encompassing [[:alpha:][:digit:]].

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

Editing

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

Unicode

By default PHP does not support Unicode, performing a byte (8-bit) search. However some characters are not represented only with 8 bits, as the case of ç which is represented by 8 bits for the c + 8 bits for the '(accent) so your search would return false, because he wouldn’t recognize the next byte in ç.
When using the modifier u you are activating a search by character and not by byte, note that this does not mean that you will consider 2 bytes but "full character".
See the conversion of some characters with this tool, such as the , which is a 3 byte character.

Related question.
Related article.

  • Also mention that the modifier u is for Unicode use, without them accents will not be recognized if they are utf8 for example. But otherwise is the best answer +1

  • 1

    @Guilhermenascimento Improvement implemented :D

5


You can use regular expressions. The function preg_match returns 1 if the string is valid, zero if not valid and FALSE if an error occurs.

To validate accented letters, numbers and hyphens:

preg_match('/^[A-Za-z0-9-]+$/u', 'lês-criolês-10');

To validate letters without accent, numbers and hyphens:

preg_match('/^[A-Za-z0-9-]+$/', 'teste-1-2-3');
  • 1

    \w = a-zA-Z0-9_, \d = 0-9, why put the \d again in expression? If he does not want the _ is not 100% correct.

  • You’re absolutely right @Guilhermelautert. I edited my answer with a more explicit set.

1

You can do it like this:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.