Regular Expression - Only number from X to Y [duplicate]
Possible Duplicate:
Regular expression where part of string must be number between 0-100
I'd like to know how to filter a variable that must be only numbers and from 1 to 300 by using regular expression on PHP. How can I do it?
P.S. I can't really find a good manual with definition of each symbol about regex. For example, what does it mean /^ or +$/i??
([1-9][0-9]?|[12][0-9][0-9]|300)
In other words, either (|
) match a number from 1 to 9 ([1-9]
), from 10 to 99 ([1-9][0-9]?
), from 100 to 299 ([12][0-9][0-9]
), or 300.
See:
- Regular Expressions Reference - Basic Syntax
- Regex Tutorial - Start of String and End of String Anchors
Don't do that -- this can become overly complicated. Just break out the number from the string, convert it to integer (if you like to) and check its value:
function match( $n ) {
preg_match( '(\d+)', $n, $matches );
return $matches && $matches[ 0 ] >= 1 && $matches[ 0 ] <= 300;
}
精彩评论