skip to Main Content

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

2

Answers


  1. 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.";
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search