PHP Stripping leading zeros 0 from a number

Rudi Strydom picture Rudi Strydom · Oct 21, 2013 · Viewed 15k times · Source

I am posting this as this isn't something most newbies may be familiar with.

The Problem

We have a ticketing system which makes use of a numeric id. Now some people in the company prefer to pre-pend zeroes to the ticket number and some people would reference it without the leading zeroes which is the correct way. So to standardize the output we have to remove the leading zeroes.

This may sound simple to do, but we can't merely run a str_replace over it as this may remove valid 0's in the middle of the number.

Now you could preg match and do all sorts of funky things to find the answer, but the simplest is to merely cast the numeric string to an int.

Let's user the following as an example:

<?php
    $correct = 45678;
    $incorrect = 0045678;

    echo $correct . '<br />';
    echo $incorrect;
?>

And you should get the following printed out:

45678

0045678

Now essentially these are the same for the application, but I would like to be able to cater for people entering the information in the incorrect format.

Answer

Jenson M John picture Jenson M John · Oct 21, 2013

Using ltrim:

$str="0045678";

$str = ltrim($str, '0');

echo $str;