I was trying to find a quick and easy method to check if the 开发者_StackOverflow社区first letter in a string is a number. A lot of the functions and methods I've seen on S.O seem over complicated. I'm wondering, would something like this work:
is_numeric($string[0]);
An easier way might be:
is_numeric(substr($string, 0, 1))
It tackles the problem of a possible empty string (that has no first character) by using substr()
. substr()
returns false
in the case of an empty string, and false
is not recognized as a number by is_numeric()
.
No, that would not work. You might get "Notice: Uninitialized string offset: 0" notice. To make it work, add strlen()
:
if ( strlen($string) > 0 && is_numeric($string[0]) ) {
}
I don't know why that answer is deleted, but the correct answer is
preg_match('/^\d/', $string);
Why? Because it provides a standard way to query strings. Normally, you have to answer many similar questions in your application:
- does a string start with a digit?
- does it contain only digits?
- does it end with a letter?
- does it contain a specific substring?
etc, etc. Without regular expressions you'd have to invent a different combination of string functions for each case, while REs provide the uniform and standard interface, which you simply reuse over and over again. This is like algebra compared to arithmetic.
Yes, it's a clean way of doing it, but use ctype_digit instead since it only allows the numbers 0 to 9 and nothing else.
It won't work on empty strings, so you should check the offset prior accessing it:
$result = isset($string[0]) ? is_numeric($string[0]) : false;
精彩评论