Search code examples
phpregexleading-zero

Count or Return Leading 0's in PHP Regex


If I have

$num = '00000567';

I want to use PHP's preg match or split to split off the 0's so I can count them or count the 0's and have the regex return the variable. Can anyone help me out as the net have very few hits about leading 0's and mostly they're about removing them


Solution

  • You can just replace all non-zero to empty string:

    $repl = preg_replace('/[^0]+/', '', $num);
    //=> 00000
    

    OR use preg_match to match zeroes only:

    if (preg_match('/^0+/', $num, $m))
       echo $m[0];