tags:

views:

109

answers:

4

I have a form where users can enter the amount they spend on their phone bill and then I tell them how much they could save if they switched to vonage, skype etc.

I pass the value "$monthlybill" in the url and then do some math to it. The problem is that if the user writes "$5" instead of "5" in the form, it breaks and is not recognized as a number. How do i strip out the dollar sign from a value?

+6  A: 
$monthlybill = str_replace("$", "", $monthlybill);

You might also want to look at the money_format function. if you are working with cash amounts.

Ólafur Waage
Thank you. As always people here saved my ass!
pg
Whenever you run into something that you think may require regex to solve, look for things like str_replace, substr_replace, substr, strrchr, etc... they can work wonders and are often easier than trying to craft a funky regex.
gaoshan88
http://www.codinghorror.com/blog/archives/001016.html
Ólafur Waage
+3  A: 

Ólafur's solution works, and is probably what I'd use, but you could also do:

$monthlybill = ltrim($monthlybill, '$');

That would remove a $ at the beginning of the string.

You can then validate further that it is a monetary amount depending on your needs.

Paolo Bergantino
A: 
function extract_decimal($str)
{
    $match = preg_match('/-?\d(\.\d+)?/', $str, $matches);
    return $match ? $matches[0] : null;
}

This function will trim away anything that isn't part of the number (including dollar signs) and also supports negative numbers and decimal values.

Alex Barrett
A: 

Considering this is user input, you'll probably want to strip all non-numeric characters from the variable.

$BillAmount = preg_replace('/[^\d.]/', '', $BillAmount);
sirlancelot