Trim any zeros at the beginning of a string using

2019-03-25 00:58发布

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?

标签: php trim
5条回答
一纸荒年 Trace。
2楼-- · 2019-03-25 01:51

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.

查看更多
贪生不怕死
3楼-- · 2019-03-25 01:51
$number = "004561";
$number = intval($number, 10);
$number = (string)$number; // if you want it to again be a string
查看更多
贼婆χ
4楼-- · 2019-03-25 01:51

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楼-- · 2019-03-25 01:52

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楼-- · 2019-03-25 02:02
ltrim($usernumber, "0");

should do the job, according to the PHP Manual

查看更多
登录 后发表回答