Ralph
Ralph

Reputation: 897

Money Regex, Optional dollar sign

I'm trying to figure out how to get the dollar sign to be optional to validate a dollar amount.

current expression:

public static function isValidDollars($amount)
{
if (preg_match("/^[0-9]*(\.[0-9][0-9])?$/", $amount){return true;}
else {return false;}
}

If I add "\$\?" to the beginning it doesn't work. I know the dollar sign has to be escaped, I'm not sure what I'm missing because this should pretty simple.

Upvotes: 1

Views: 431

Answers (1)

anubhava
anubhava

Reputation: 786091

  1. Make sure to use single quote
  2. Escape the dollar character $
  3. make it optional

Your regex:

'/^\$?[0-9]*(\.[0-9][0-9])?$/'

Upvotes: 4

Related Questions