在php中检测字符串中的第一个零

问题描述:

function number_check($int){
    if($int>0 && !is_float($int)){return TRUE;}
    else{return FALSE;}
}

$var="025";

if(number_check($var)){echo "pass";}else{echo "fail";}

I have make a function to check the number for post id.

post_id should always > 0 and no decimal.

but I have a problem when user try to enter 000243, if user put zero at front, it return true.

Is any way to solve this?

  function number_check($ int){
 if($ int> 0&&!is_float  ($ int)){return TRUE;} 
 else {return FALSE;} 
} 
 
 $ var =“025”; 
 
if(number_check($ var)){echo“pass”;}  else {echo“fail”;} 
  code>  pre> 
 
 

我已经创建了一个函数来检查post id的编号。 p>

post_id code>应始终> 0 code>并且没有小数。 p>

但是当用户尝试输入 000243 code>时,如果用户输入 0 code>,我会遇到问题 在前面,它返回 true code>。 p>

有什么方法可以解决这个问题吗? p> div>

I think checking $int{0} != 0 will solve what you are trying to achieve :

function number_check($int){
    if ( $int > 0 && !is_float($int) && $int{0} != 0 ) {
        return TRUE;
    }
    else {
        return FALSE;
    }
}

$var="023";

if ( number_check($var) ) {
    echo "pass";
} else {
    echo "fail";
}

Check this DEMO

try this:

<?php
echo intval('000243');
?>

try to assign value to $var without using quotes. i.e $var = 000243;

Another way to do that is the following:

function prepareID($id)
{
    $id = preg_replace('/^([0]*)/', '', $id);

    return (int)$id;
}

$var = prepareID("025");

The prepareID function will remove any leading zeros and it will return an integer