【问题标题】:How do I validate first 2 letter or numbers in a string in PHP? [duplicate]如何在 PHP 中验证字符串中的前 2 个字母或数字? [复制]
【发布时间】:2023-02-22 19:59:17
【问题描述】:

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

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

【问题讨论】:

  • “但仍然有我不想只检查整个字符串的第一个字符的问题”- 是什么阻止了您研究诸如“如何从 PHP 中的字符串中获取前两个字符”这样的琐碎事情……?请多出点实际的努力,你问。 How much research effort is expected of Stack Overflow users?

标签: php validation


【解决方案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.";
}

【讨论】:

【解决方案2】:

您可以简单地get the first two characters of the string on their own,并验证:

$str = "1234kjhgkdfkgjh";

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

演示:https://3v4l.org/7IHJa

或者你可以使用正则表达式,按照robotiaga's answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多