tags:

views:

306

answers:

5

Is there a simple way to remove a leading zero (as in 01 becoming 1)?

+5  A: 
$str = "01";
echo intval($str);
Tomalak
Maybe it's worth putting an is_numeric() block around it to catch cases where $str is not a number, since intval returns 0 on failure: http://fr.php.net/manual/en/function.intval.php
Michael Stum
A: 

Just multiply by 1

echo "01"*1
J.D. Fitz.Gerald
Works, but only as long as the string is a number. :-)
Tomalak
is this a serious answer? I can't tell.
Jeff Atwood
The classic, Add-an-aritmetic-calculation-that-doesnt-change-the-original-value-to-make-the-compiler-cast-it-to-a-numeric-value-trick! ;)
Stefan
This is not a good way to do this.
epochwolf
@Jeff Atwood: I'm guessing this is a serious answer. So many PHP programmers are self-taught and know how to get the job done, not how to get it done *right*[email protected]. Fitz.Gerald: Sorry that you're being dogged. This really peeves CS people. It's not an explicit solution to the problem.
Lucas Oman
@epochwolf - why is this not a good way to do this? I have previously advocated $str_value + 0 to convert a number-in-a-string to a number.
staticsan
A: 

Regex replace /^0*/ with '' for a string return solution

annakata
+10  A: 

You can use the ltrim function.

ltrim($str,"0");

Matt
+1  A: 

if you use the trim functions, you might mistakenly remove some other character, like by triming "12" your will have "2". use the intval() function. this function will convert your string (which could start by a leading zero or not) to an integer value. intval("02") will be 2 and intval ("32") wll be 32.

farzad