-1

I need to validate a string to check if the first two characters in a string are numbers.

I tried using in numeric but still had the issue that I did not want to check the whole string only the first two characters..

mark_b
  • 1,393
  • 10
  • 18
  • 2
    _"but still had the issue that I did not want to check the whole string only the first to characters"_ - and what stopped you from researching such a trivial thing as "how do I get the first two characters from a string in PHP" ...? Please show a bit more actual effort, _before_ you ask. [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/1427878) – CBroe Feb 22 '23 at 11:43

2 Answers2

2

This can be done using a Regular Expression

$string = "12example";
if (preg_match("/^[0-9]{2}/", $string)) {
    echo "The first two characters are numbers.";
} else {
    echo "The first two characters are not numbers.";
}
ADyson
  • 57,178
  • 14
  • 51
  • 63
robotiaga
  • 315
  • 2
  • 11
0

You can simply get the first two characters of the string on their own, and validate that:

$str = "1234kjhgkdfkgjh";

$result = ctype_digit(substr($str, 0, 2));
var_dump($result);

demo: https://3v4l.org/C33ui.

Or you could use a Regular Expression, as per robotiaga's answer

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • I think the preg match solution works better. When the string is `.1.b2example` it also returns true. So for your example there also needs some proper validation first – Baracuda078 Feb 22 '23 at 13:14
  • @Baracuda078 True, good point. I think using `is_int` would fix that - demo: https://3v4l.org/M5JN6 . I have updated the answer. – ADyson Feb 22 '23 at 13:15
  • Sorry to say but that's also not working. The return type of `substr` is a `fasle|string` so you also get `false` in this case – Baracuda078 Feb 22 '23 at 13:21
  • @Baracuda078 my apologies, trying to rush too much. ctype_digit would do it. https://3v4l.org/C33ui – ADyson Feb 22 '23 at 13:30