First letter is number in string

后端 未结 5 2037
忘掉有多难
忘掉有多难 2020-12-11 01:55

I was trying to find a quick and easy method to check if the first letter in a string is a number. A lot of the functions and methods I\'ve seen on S.O seem over complicated

相关标签:
5条回答
  • 2020-12-11 02:17

    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().

    0 讨论(0)
  • 2020-12-11 02:19

    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.

    0 讨论(0)
  • 2020-12-11 02:23

    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.

    0 讨论(0)
  • 2020-12-11 02:34

    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;
    
    0 讨论(0)
  • 2020-12-11 02:38

    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]) ) {
    }
    
    0 讨论(0)
提交回复
热议问题