PHP remove first zeros

房东的猫 提交于 2019-12-04 16:05:44

问题


Want to remove all 0 placed at the beginning of some variable.

Some options:

  1. if $var = 0002, we should strip first 000 ($var = 2)
  2. if var = 0203410 we should remove first 0 ($var = 203410)
  3. if var = 20000 - do nothing ($var = 20000)

What is the solution?


回答1:


cast it to integer

$var = (int)$var;



回答2:


Maybe ltrim?

$var = ltrim($var, '0');



回答3:


$var = ltrim($var, '0');

This only works on strings, numbers starting with a 0 will be interpreted as octal numbers, multiple zero's are ignored.




回答4:


$var = strval(intval($var));

or if you don't care about it remaining a string, just convert to int and leave it at that.




回答5:


Just use + inside variables:

echo +$var;



回答6:


Multiple it by 1

$var = "0000000000010";
print $var*1;  

//prints 10



回答7:


Carefull on the casting type;

var_dump([
    '0014010011071152',
    '0014010011071152'*1,
    (int)'0014010011071152',
    intval('0014010011071152')
]);

Prints:

array(4) {
    [0]=> string(16) "0014010011071152"
    [1]=> float(14010011071152)
    [2]=> int(2147483647)
    [3]=> int(2147483647)
}


来源:https://stackoverflow.com/questions/3563740/php-remove-first-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!