string formatting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dannyd
Forum Commoner
Posts: 56
Joined: Wed Jan 23, 2008 11:31 am

string formatting

Post by dannyd »

Hi,

If I have the following

00030
00005
02830
00002
00200

How do I remove the 0's preceding 0's so after formatted it looks like

30
5
2830
2
200


?????
dannyd
Forum Commoner
Posts: 56
Joined: Wed Jan 23, 2008 11:31 am

Re: string formatting

Post by dannyd »

I thought of using ltrim but i dont think that works with characters. Is there a php function that will remove preceding 0's starting from the left ?
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Re: string formatting

Post by liljester »

try the number_format() function.

Code: Select all

$number = "00300";
print number_format($number);
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: string formatting

Post by pickle »

PHP Manual wrote:ltrim — Strip whitespace (or other characters) from the beginning of a string
ltrim() is built to strip characters...so it'll work with characters.

Both ltrim() and number_format() would work, though without doing any testing, I'd guess ltrim() would be a few nanoseconds faster, though number_format() is probably the better choice, as you are formatting numbers.

You could also just add zero to all the numbers & print the result. I believe casting them to integers should also do the trick.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply