Nico Sanchez
Nico Sanchez

Reputation: 23

Using preg_match to validate a nickname without spaces and letter variations

I'm having problems with the way I validate nicknames:

preg_match("^[A-Za-z0-9]+$^", $nickname );

It works right but have one problem with it, which I can't fix, is that it allows white spaces and letter variations such as é, ç, ñ and I don't want to allow those. How can I fix it?

Upvotes: 0

Views: 208

Answers (1)

jmarkmurphy
jmarkmurphy

Reputation: 11473

I think that you should use /^[A-Za-z0-9]+$/. The ^ means beginning of the line, and $ means end of the line. By wrapping your string in ^ you are making that the regex delimiter rather than the typical /. In this case ^ looses it's meaning of beginning of the line.

Edit: Better still is /\A[A-Za-z0-9]+\z/. This is a subtle modification. ^ could be the beginning of a line or the beginning of the string but \A is always the beginning of the string. Likewise $ could be the end of a line or the end of the string but \z is the end of the string. So by using ^ and $, nicknames could contain linebreaks, but if you use \A and \z they can't.

Upvotes: 3

Related Questions