Reputation: 2531
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?
Upvotes: 0
Views: 187
Reputation: 17512
Considering this is user input, you'll probably want to strip all non-numeric characters from the variable.
$BillAmount = preg_replace('/[^\d.]/', '', $BillAmount);
Upvotes: 0
Reputation: 16465
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.
Upvotes: 0
Reputation: 488444
Ó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.
Upvotes: 3
Reputation: 70001
$monthlybill = str_replace("$", "", $monthlybill);
You might also want to look at the money_format function. if you are working with cash amounts.
Upvotes: 7