PHP 删除第一个零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3563740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:14:42  来源:igfitidea点击:

PHP remove first zeros

phpformattingstring-formattingzeronumber-formatting

提问by James

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

想去掉所有0放在开头的某个变量。

Some options:

一些选项:

  1. if $var = 0002, we should strip first 000($var = 2)
  2. if var = 0203410we should remove first 0($var = 203410)
  3. if var = 20000- do nothing ($var = 20000)
  1. 如果$var = 0002,我们应该先剥离000( $var = 2)
  2. 如果var = 0203410我们应该先删除0( $var = 203410)
  3. 如果var = 20000- 什么都不做 ( $var = 20000)

What is the solution?

解决办法是什么?

回答by drAlberT

cast it to integer

将其强制转换为整数

$var = (int)$var;

回答by robertbasic

Maybe ltrim?

也许ltrim

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

回答by Lekensteyn

$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.

这仅适用于字符串,以 0 开头的数字将被解释为八进制数,多个零将被忽略。

回答by poostchi

Just use + inside variables:

只需使用 + 内部变量:

echo +$var;

回答by Amber

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

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

或者如果您不关心它是否仍然是一个字符串,只需转换为 int 并保留它。

回答by Jhourlad Estrella

Multiple it by 1

乘以 1

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

//prints 10

回答by Martijn Hoogstraten

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)
}