How to remove all leading zeroes in a string

前端 未结 10 1146
感情败类
感情败类 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 07:46

    I don't think preg_replace is the answer.. old thread but just happen to looking for this today. ltrim and (int) casting is the winner.

    <?php
     $numString = "0000001123000";
     $actualInt = "1123000";
    
     $fixed_str1 = preg_replace('/000+/','',$numString);
     $fixed_str2 = ltrim($numString, '0');
     $fixed_str3 = (int)$numString;
    
     echo $numString . " Original";
     echo "<br>"; 
     echo $fixed_str1 . " Fix1";
     echo "<br>"; 
     echo $fixed_str2 . " Fix2";
     echo "<br>";
     echo $fixed_str3 . " Fix3";
     echo "<br>";
     echo $actualInt . " Actual integer in string";
    
     //output
    
     0000001123000 Origina
     1123 Fix1
     1123000 Fix2
     1123000 Fix3
     1123000 Actual integer in tring
    
    0 讨论(0)
  • 2020-12-02 07:50
    (string)((int)"00000234892839")
    
    0 讨论(0)
  • 2020-12-02 07:51

    Regex was proposed already, but not correctly:

    <?php
        $number = '00000004523423400023402340240';
        $withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
        echo $withoutLeadingZeroes;
    ?>
    

    output is then:

    4523423400023402340240
    

    Background on Regex: the ^ signals beginning of string and the + sign signals more or none of the preceding sign. Therefore, the regex ^0+ matches all zeroes at the beginning of a string.

    0 讨论(0)
  • 2020-12-02 07:53

    Ajay Kumar offers the simplest echo +$numString; I use these:

    echo round($val = "0005");
    echo $val = 0005;
        //both output 5
    echo round($val = 00000648370000075845);
    echo round($val = "00000648370000075845");
        //output 648370000075845, no need to care about the other zeroes in the number
        //like with regex or comparative functions. Works w/wo single/double quotes
    

    Actually any math function will take the number from the "string" and treat it like so. It's much simpler than any regex or comparative functions. I saw that in php.net, don't remember where.

    0 讨论(0)
  • 2020-12-02 07:55

    ltrim:

    $str = ltrim($str, '0');
    
    0 讨论(0)
  • 2020-12-02 07:59

    Assuming you want a run-on of three or more zeros to be removed and your example is one string:

        $test_str ="0002030050400000234892839000239074";
        $fixed_str = preg_replace('/000+/','',$test_str);
    

    You can make the regex pattern fit what you need if my assumptions are off.

    This help?

    0 讨论(0)
提交回复
热议问题