php substring regex
I've been reading php code all day and what I can't seem to find an answer to what I believe is a simple question.
I've got an array full of strings and I want to see if the first character in a string is a number, then do something with it, e.g:
if substr($stringArray[$i],0,1) == regexsomething[0-9]) { do stuff }
Have I got this all wrong?
Surely I could set the regex to be [^0-9] to match at the start but the PHP preg_match is confusing me greatly.
Any advice would be super.
Than开发者_高级运维ks
Outside brackets, ^
means "start", but right after a [
, it means "invert this whole class". /[^0-9]/
would match anything that contains a non-digit. A regular expression to match a single digit would be:
/^[0-9]$/
PHP already has a function for this, though: is_numeric()
if ( is_numeric( substr( $stringArray[$i],0,1 ) ) ) { do stuff }
If you want to go the regex route, you won't need to get the first character. A regex that matches anything that starts with a digit would be:
if ( preg_match( '/^[0-9]/', $stringArray[$i] ) ) { do stuff }
If you wnat to make sure that a string is a number you can use is_numeric
like so:
if(is_numeric($string))
{
//Do Something
}
If you want to make sure its a single digit like 7
you can use the <
less-than operator
if(is_numeric($string) && $string < 10)
{
//Do Something
}
精彩评论