How can I strip "$5,000" to just "5000"?

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
carmen.smth1
Forum Newbie
Posts: 8
Joined: Mon Sep 29, 2008 12:45 pm

How can I strip "$5,000" to just "5000"?

Post by carmen.smth1 »

Or any number in that format like $24,900 to just 24900. Then turn it back? I need to make a script that will take a price and automatically add a certain amount like $24,900 should be $26,900 but I need to strip the numbers before I can use the addition function.

Any ideas? Thank you!
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: How can I strip "$5,000" to just "5000"?

Post by Mark Baker »

Code: Select all

 
 
$string = '$24,900';
echo $string.'<br />';
 
$number = str_replace(array('$',','), array('',''), $string);
echo $number.'<br />';
 
$reformatted = '$'.number_format($number);
echo $reformatted.'<br />';
 
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: How can I strip "$5,000" to just "5000"?

Post by Christopher »

Or to get everything but digits:

Code: Select all

$number = preg_replace('/[^0-9]/', '', $string);
(#10850)
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Re: How can I strip "$5,000" to just "5000"?

Post by jmut »

Should be very careful with this. If this thingy is localazied you can get very funky results. As comman might mean fraction delimitar or thousands or god knows what else in different locales.
Your best option is to do the math before view and then properly render it. If you're doing a post processing and not in control of all...should be clear on what might expect.
Post Reply