adam84 Posted August 27, 2011 Share Posted August 27, 2011 I am trying to only allow letters, hyphens, periods and spacings Any suggestions would be helpful. function checkName( $name ){ if(!eregi("[a-zA-Z.' ]+", $name)) return false; return true; } Thank you Quote Link to comment Share on other sites More sharing options...
.josh Posted August 27, 2011 Share Posted August 27, 2011 if (!preg_match("~^[a-z. -]+$~i",$name)) { Quote Link to comment Share on other sites More sharing options...
sasa Posted August 27, 2011 Share Posted August 27, 2011 try function checkName( $name ){ if(preg_match("/[^a-zA-Z.' ]/", $name)) return false; return true; } Quote Link to comment Share on other sites More sharing options...
.josh Posted August 27, 2011 Share Posted August 27, 2011 @sasa: sure, checking for presence of characters NOT acceptable is an alternate way to go. However, it looks like you just c/p'd his base pattern, which doesn't match what he actually says he wants to match for. He says hyphens are acceptable, and he did not mention single quotes. @adam84: FYI neither of these addresses a couple of issues that are commonly addressed with. - These regexes do not account for length limits. Most sites want a name to have a minimum amount of characters, or at least limit the maximum. - These regexes do not prevent values like "---------" or " " or "- - - - - -" or ".....---.-- ---" or...you get the picture. Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted August 27, 2011 Share Posted August 27, 2011 Based strictly on the OP question, you could also do it without using a pattern at all. function checkName($name) { if( ctype_alpha( str_replace(array('-', ' ', '.'), '', $name)) ) { return TRUE; } else { return FALSE; } } Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 28, 2011 Share Posted August 28, 2011 Just an FYI. If you need a function that is supposed to return a Boolean then it is not necessary to do something such as if($foo==$bar) { return true; } else { return false; } Just return the comparison. Using Pikachu's solution as an example: function checkName($name) { return (ctype_alpha( str_replace(array('-', ' ', '.'), '', $name)) ); } Quote Link to comment Share on other sites More sharing options...
nina_ Posted August 28, 2011 Share Posted August 28, 2011 I am trying to only allow letters, hyphens, periods and spacings if (trim($string, 'a..zA..Z-. ') === '') { echo "$string is valid"; } 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.