Jessica Posted December 23, 2006 Share Posted December 23, 2006 I want to allow only letters, numbers, and the . and _ character - nothing else, no spaces, no $!, etc. This is what I have.[code]if(preg_match("/[^A-Za-z0-9_\.]+$/", $this->username)){ $msg = "Please use only letters, numbers, and the following characters: _ and .";}else{ $msg = "Username OK!";}[/code]It works great when a user enters !@#$% etc, but when a user enters spaces in between two words, IE: john doe, it says Username OK. If they enter a space and another unallowed character it gives the error, but not if it's just two words with space. What is wrong with my regexp? Quote Link to comment Share on other sites More sharing options...
c4onastick Posted December 23, 2006 Share Posted December 23, 2006 Jesi,What you've got there looks good. Just a few minor tweaks, I'd add:[code]if(!preg_match('/^[A-Za-z0-9_.]+$/', $this->username)){ $msg = "Please use only letters, numbers, and the following characters: _ and .";}else{ $msg = "Username OK!";}[/code]I usually use a negated match (!preg_match(...)) instead of negated character classes ([^...]) in this situation. It'll work either way, just makes it easier to debug later I think (just my opinion). You sometimes run into problems with portability when you use negated classes (unicode characters start sneaking in, it gets ugly).Two things: you don't need to escape the '.' (dot) character inside character classes. All I did was add the '^' (beginning of line/string) anchor to the start of it! That way it'll require the engine to match one of those characters in the class from the start all the way to the '$' (end of string position). The problem you had with the leading space was because the engine would fail there and exclude that from the match since it was only anchored to the end of the string.Enjoy! Quote Link to comment Share on other sites More sharing options...
Jessica Posted December 23, 2006 Author Share Posted December 23, 2006 Thanks! I am not sure why I was escaping the . - this is the first regexp I have written and despite reading a ton of tutorials and a quick reference book, I still just can't get my mind around it. It works beautifully now, thanks a ton! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.