Woodburn2006 Posted September 21, 2007 Share Posted September 21, 2007 How do you determine that na input should only be numbers? for example i ise this line do check the stringlength of an input: if(strlen($year) != 4){$error[] = "year";} how would i use that to check if the input is just numbers? Link to comment https://forums.phpfreaks.com/topic/70185-numbers-only/ Share on other sites More sharing options...
MmmVomit Posted September 21, 2007 Share Posted September 21, 2007 There are several different ways to do that. ctype_digit($year) will do what you want. This might also be a good time to play around with regular expressions. preg_match('/^[0-9]*$/', $year) will also do the same thing. Link to comment https://forums.phpfreaks.com/topic/70185-numbers-only/#findComment-352525 Share on other sites More sharing options...
php_dave Posted September 21, 2007 Share Posted September 21, 2007 Hey, This should work preg_match("/^[0-9]+$/", $year); Edit - Cross post! Link to comment https://forums.phpfreaks.com/topic/70185-numbers-only/#findComment-352526 Share on other sites More sharing options...
recklessgeneral Posted September 21, 2007 Share Posted September 21, 2007 I'll add a bit to the other regular expressions. This one restricts the length to 4 characters and makes it more year like by restricting the range of the first digit to 1 or 2: preg_match("/^[1-2][0-9]{3}$/", $year); Link to comment https://forums.phpfreaks.com/topic/70185-numbers-only/#findComment-352529 Share on other sites More sharing options...
MmmVomit Posted September 21, 2007 Share Posted September 21, 2007 Yes, my regex-fu is still very weak. Link to comment https://forums.phpfreaks.com/topic/70185-numbers-only/#findComment-352535 Share on other sites More sharing options...
Woodburn2006 Posted September 21, 2007 Author Share Posted September 21, 2007 in what way would i use this? im new to the php game i put it as this but when i put in a valid date i get the error if(preg_match("/^[1-2][0-9]{3}$/", $year)){$error[] = "year";} Link to comment https://forums.phpfreaks.com/topic/70185-numbers-only/#findComment-352539 Share on other sites More sharing options...
MmmVomit Posted September 21, 2007 Share Posted September 21, 2007 Just add in a logical not. preg_match($regex, $string) returns a boolean. You can think of $regex as a set of rules that a string has to follow. In this case '/^[1-2][0-9]{3}$/' means "Starts with a one or two and is followed by three digits." If $string follows all the rules, preg_match returns true. Link to comment https://forums.phpfreaks.com/topic/70185-numbers-only/#findComment-352556 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.