4

Is there a way to check if the first character of a string is a letter or a number? I'm not really sure what function to use. Is there a way to check not using regex, as we have not learned that yet in my class.

Gurpal Rattu
  • 99
  • 1
  • 6
  • 1
    Have you tried something? – Rizier123 Mar 13 '15 at 18:31
  • 2
    @bcesars how exactly is that helpful to the question? – Jonathan Kuhn Mar 13 '15 at 18:37
  • 1
    @JonathanKuhn How exactly this question is valid in SO without being _too broad_ or _primarily opinion based_ ? – bcesars Mar 13 '15 at 18:41
  • [Get the first character](http://stackoverflow.com/questions/1972100/getting-the-first-character-of-a-string-with-str0) and then [check if it is a number](http://stackoverflow.com/questions/14230986/how-can-i-check-if-a-char-is-a-letter-or-a-number) – Rick Smith Mar 13 '15 at 19:02

2 Answers2

5

I'd encourage you to read more about strings in PHP. For example, you can dereference them like arrays to get individual characters.

$letters = 'abcd';
echo $letters[0];

There are also a handful of ctype functions. Check out, ctype_digit() and [ctype_alpha()}(http://php.net/manual/en/function.ctype-alpha.php).

ctype_digit($letters[0]); // false
ctype_alpha($letters[0]); // true

Putting these together, you should be able to do what you want.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
4

You can access characters in a string just like an array index, so $string[0] is the first character.

Then you could use is_numeric to determine if the first character is a number.

$word1 = "string";
$word2 = "12345";

var_dump(is_numeric($word1[0])); // false
var_dump(is_numeric($word2[0])); // true

This should get you pretty close to what you're looking for, depending on how strictly you define a "letter." I'm guessing that you really mean "non-numeric."

jszobody
  • 28,495
  • 6
  • 61
  • 72