21

I’d like to give my users the option to not only fill in letters and numbers, but also “special” letters like the “á”, “é”, etc. However, I do not want them to be able to use symbols like “!”, “@”, "%”, etc.

Is there a way to write a regex to accomplish this? (Preferably without specifying each special letter.)

Now I have:

$reg = '/^[\w\-]*$/';

3 Answers 3

42

You could use Unicode character properties to describe the characters:

/^[\p{L}-]*$/u

\p{L} describes the class of Unicode letter characters.

Sign up to request clarification or add additional context in comments.

1 Comment

don't forget to add modifier u at the end : /u to select UTF-8 mode … php.net/manual/fr/regexp.reference.unicode.php#118693
5

What characters are considered "word-characters" depends on the locale. You should set a locale which has those characters in its natural alphabet, and use the /u modifier for the regexp, like this:

$str = 'perché';
setlocale(LC_ALL, 'it_IT@euro');
echo preg_match('#^\w+$#u', $str);

1 Comment

doesn't seem to work either. But Gumbo's solution worked. Thanks for the reply
4

you can try with this regex:

$reg = '~[^\\pL\d]+~u';

which catch also accented characters

1 Comment

doesn't seem to work on my server. But Gumbo's answer worked. Thanks for the reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.