PHP Stripping leading zeros 0 from a number

15.7k Views Asked by At

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.

3

There are 3 best solutions below

1
On

Simplest Solution

As they say the simplest solution is often the best. And what is easier than telling PHP that this is an integer we are working with. We do this by pre-pending (int) to tell PHP that we are working with an integer.

Using the previous example:

<?php
    $correct = 45678;
    $incorrect = (int)0045678;

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

And you should get the following printed out:

45678

45678

I know it seems self explanatory, but I only learnt about type casting a couple of years into website development. Maybe you will find this of use.

0
On

you can also use ltrim() http://de3.php.net/manual/en/function.ltrim.php this removes the desired char from the left

0
On

Using ltrim:

$str="0045678";

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

echo $str;