如何在 PHP 中验证字符串中的前 2 个字母或数字? [重复]

问题描述 投票:0回答:2

我需要验证一个字符串以检查字符串中的第一个字符是否是数字。而且我不知道如何解决这个问题。

尝试在数字中使用但仍然有我不想只检查整个字符串的第一个到字符的问题..

php validation
2个回答
1
投票

这可以使用正则表达式来完成

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

0
投票

您可以简单地自己获取字符串的前两个字符,并验证that

$str = "1234kjhgkdfkgjh";

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

演示:https://3v4l.org/GD75P.

或者您可以使用正则表达式,根据 robotiaga 的回答

© www.soinside.com 2019 - 2024. All rights reserved.