If语句检查第一个字符是否为数字


If statement to check if first character is a number

我需要一个php-if语句来检查字符串的第一个字符是否是数字,但我不确定如何做到这一点,我已经尝试了一些不起作用的方法。我的基本代码在下面,上面写着"一个数字",这是我需要它来识别第一个字符的地方。

if ($row['left_button_link'] == a number) 
{
printf('hello');
}
else 
{
printf('bye bye');
}

此外,我该如何在该语句中添加第三个复选框。if正在检查一个数字,else字符串将以"/"开头,但如果我想要第三个选项,如果字符串为空,根本没有字符,我该如何添加?

谢谢你的帮助。

有一些内置函数可以满足您的需要。

  • CCD_ 1以检查是否为数字
  • substr()或类似程序,用于检查第一个字符是否为某物
  • 用于检查字符串是否为空的empty()

检查它是否是一个数字:

if( is_numeric(substr($string,0, 1))  ){
echo "it is a number";
}

正如N.B在下面评论的那样,您可以将字符串视为数组,这也应该有效:

if( is_numeric($string[0]) ) {
    echo "it is a number";
}

因此,当我们应用所有这些时,您的代码应该看起来像:

$var = $row['left_button_link'];
if( is_numeric($var[0]) ) 
{
    echo "It starts with a number!";
}
elseif ( $var[0] == '/' )
{
    echo "Uh oh, first character is a slash";
}
elseif( empty($var) ) {
    echo "Bye bye";
}

希望这能有所帮助!

您可以使用is_numeric函数:

is_numeric($str[0])

所以最终产品应该是:

if (is_numeric($row['left_button_link'][0])) {  // check if first char is numeric
    printf('hello');
}
elseif ($row['left_button_link'][0] == '/') {   // check if first char is '/'
    printf('First char is /');
}
elseif (empty($row['left_button_link'])) {      // check if string is empty
    printf('Empty!');
}
else{
    printf('bye bye');
}
is_numeric(substr($string, 0, 1))
if (is_numeric(substr($row['left_button_link'], 0, 1))){
    //do something
}

可能是这样的:

if(preg_match('/^'d/,$input)) {
    echo "First char is a digit.";
}

对于问题a,use is_numeric()对于问题b,使用elseif (...)

if (is_numeric($row['left_button_link'][0])) {
    printf('hello');
    }
elseif (empty($row['left_button_link'])){
    printf('String is empty');
    }
else{
    printf('bye bye');
    }

HTH(尽管对于这么简单的问题,你应该认真地在手册中查找)

if(ctype_digit($row['left_button_link'][0]))
{
    //First char is numeric
}
else if($row['left_button_link'][0] == '/')
{
    //First char is "/"
}
else if(trim($row['left_button_link']) == '')
{
    //String is completely empty
}
else
{
    //Something else
}

使用empty()检查字符串是否为空时要小心——它只能可靠地用于数组。empty()在传递"时将返回false-将trim()的输出与"进行比较更可靠