How to strip variable and add comas where needed?

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
tech0925
Forum Commoner
Posts: 47
Joined: Wed Nov 09, 2011 2:46 pm

How to strip variable and add comas where needed?

Post by tech0925 »

I was wondering if someone could tell me how to properly strip and add comas to numbers. I currently have numbers being entered into my database without comas.

Can someone show me a good way to make sure that the info being entered in is a number and how to strip the variable leaving only numbers. Then properly adding comas where they should be. I am referring to the money system. Here are some possible results:

12,583,573
or
22,684,593.85
or
1,348.21

Not sure how to google this one. Thanks!
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How to strip variable and add comas where needed?

Post by Celauran »

Strip everything but digits and decimals:

Code: Select all

$input = preg_replace( '/[^\d\.]/', '', $input );
For formatting, check number_format() or, perhaps better, money_format()
tech0925
Forum Commoner
Posts: 47
Joined: Wed Nov 09, 2011 2:46 pm

Re: How to strip variable and add comas where needed?

Post by tech0925 »

Oh ok, thanks once again 4 your help!!

Cheers!
Post Reply