Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First letter is number in string

Tags:

php

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. I'm wondering, would something like this work:

is_numeric($string[0]);
like image 309
Riess Howder Avatar asked Jun 07 '11 10:06

Riess Howder


3 Answers

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

like image 110
kapa Avatar answered Oct 20 '22 00:10

kapa


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]) ) {
}
like image 27
binaryLV Avatar answered Oct 19 '22 22:10

binaryLV


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.

like image 21
user187291 Avatar answered Oct 20 '22 00:10

user187291