How to remove all leading zeroes in a string

前端 未结 10 1123
感情败类
感情败类 2020-12-02 07:16

If I have a string

00020300504
00000234892839
000239074

how can I get rid of the leading zeroes so that I will only have this



        
相关标签:
10条回答
  • 2020-12-02 08:01

    Don't know why people are using so complex methods to achieve such a simple thing! And regex? Wow!

    Here you go, the easiest and simplest way (as explained here: https://nabtron.com/kiss-code/ ):

    $a = '000000000000001';
    $a += 0;
    
    echo $a; // will output 1
    
    0 讨论(0)
  • 2020-12-02 08:05

    you can add "+" in your variable,

    example :

    $numString = "0000001123000";
    echo +$numString;
    
    0 讨论(0)
  • 2020-12-02 08:07

    Im Fixed with this way.

    its very simple. only pass a string its remove zero start of string.

    function removeZeroString($str='')
    {
        while(trim(substr($str,0,1)) === '0')
        {
            $str = ltrim($str,'0');
        }
        return $str;
    }
    
    0 讨论(0)
  • 2020-12-02 08:10

    Similar to another suggestion, except will not obliterate actual zero:

    if (ltrim($str, '0') != '') {
        $str = ltrim($str, '0');
    } else {
        $str = '0';
    }
    

    Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:

    $str = ltrim($str, '0') ?: '0'; 
    
    0 讨论(0)
提交回复
热议问题