pg.
pg.

Reputation: 2531

Stripping $ from php values

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

Answers (4)

matpie
matpie

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

Alex Barrett
Alex Barrett

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

Paolo Bergantino
Paolo Bergantino

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

Ólafur Waage
Ólafur Waage

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

Related Questions