Search code examples
phpregexnullpreg-replacezero

Removing ending zeros with one simple preg_replace?


i would remove the ending zeros with php_replace and i would have a better function like this.

Value:

$value = 123.12300;

Current function:

return preg_match('#[.,][0-9]+[0]+$#', $value) ? preg_replace('#[0]+$#', '', $value) : $value;

Another function:

return preg_replace('#([.,]{0,1}\d+)[0]+$#', '\\1', $value);

Thank you in advance!


Solution

  • [0-9]+, \d+ match greedily. (match as much as possible). It could match one of trailing 0. So use non-greedy version \d*?.

    And [.,]{0,1} could make the pattern match even if that is no . or ,. Just use [.,].

    $pattern = '#([.,]\d*?)0+$|[.,]$#';
    
    var_dump(preg_replace($pattern, '\1', '123.12300'));
    # => 123.123
    var_dump(preg_replace($pattern, '\1', '1234000'));
    # => 1234000
    var_dump(preg_replace($pattern, '\1', '123456780.000000100'));
    # => 123456780.0000001
    var_dump(preg_replace($pattern, '\1', '123456780.'));
    # => 123456780