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..
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..
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.";
}
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