Trim any zeros at the beginning of a string using PHP

后端 未结 6 1890
庸人自扰
庸人自扰 2021-02-13 17:59

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 dig

相关标签:
6条回答
  • 2021-02-13 18:22

    Just multiply your number by zero.

    $input=$input*1;
    //000000123*1 = 123
    
    0 讨论(0)
  • 2021-02-13 18:25
    ltrim($usernumber, "0");
    

    should do the job, according to the PHP Manual

    0 讨论(0)
  • 2021-02-13 18:26

    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"
    
    0 讨论(0)
  • 2021-02-13 18:27
    $number = "004561";
    $number = intval($number, 10);
    $number = (string)$number; // if you want it to again be a string
    
    0 讨论(0)
  • 2021-02-13 18:29

    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.

    0 讨论(0)
  • 2021-02-13 18:32

    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"
    
    0 讨论(0)
提交回复
热议问题