Trim any zeros at the beginning of a string using PHP

拜拜、爱过 提交于 2019-12-04 18:07:34

问题


Users will be filling a field in with numbers relating to their account. Unfortunately, some users will have zeroes prefixed to the beginning of the number to make up a six digit number (e.g. 000123, 001234) and others won't (e.g. 123, 1234). I want to 'trim' the numbers from users that have been prefixed with zeros in front so if a user enters 000123, it will remove the zeroes to become 123.

I've had a look at trim and substr but I don't believe these will do the job?


回答1:


You can use ltrim() and pass the characters that should be removed as second parameter:

$input = ltrim($input, '0');
// 000123 -> 123

ltrim only removes the specified characters (default white space) from the beginning (left side) of the string.




回答2:


ltrim($usernumber, "0");

should do the job, according to the PHP Manual




回答3:


$number = "004561";
$number = intval($number, 10);
$number = (string)$number; // if you want it to again be a string



回答4:


You can always force PHP to parse this as an int. If you need to, you can convert it back to a string later

(int) "000123"



回答5:


You can drop the leading zeros by converting from a string to a number and back again. For example:

$str = '000006767';
echo ''.+$str; // echo "6767"



回答6:


Just multiply your number by zero.

$input=$input*1;
//000000123*1 = 123


来源:https://stackoverflow.com/questions/3782414/trim-any-zeros-at-the-beginning-of-a-string-using-php

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