First letter is number in string

后端 未结 5 2040
忘掉有多难
忘掉有多难 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: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.

提交回复
热议问题