Ravi Soni
Ravi Soni

Reputation: 2250

Regex to get currency and amount from string

I have an Regex with me preg_match('/(?<=\$)\d+(\.\d+)?\b/', $str, $regs which return me the amount in a currency, but what i am trying is to get the symbol associated with the amount too.

1) E.g. the string is $300.00 asking price should return $300.00 but now it returns 300
2) E.g. the string is EUR 300.00 should return EUR300.00 but now it returns 300

Simply i want the currency with amount.

Thanks

Upvotes: 4

Views: 12533

Answers (4)

Miguel Q
Miguel Q

Reputation: 3628

If you want just the amount part for any Symbol :

preg_match_all("/([0-9]+[.]*)/", $t, $output_array);
$output_array=implode("",$output_array[0]);

" €12451.5651$Euro " will output: 12451.5651

Upvotes: 1

davide
davide

Reputation: 1948

Try with

/(\$|EUR)\s*(\d*\.\d+)?\b/

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173662

First, you match the currency which can be either $ or EUR, followed by optional white space:

(?:EUR|[$])\s*

Then, match the main digit group, followed by an optional period and two digits:

\d+(?:\.\d{2})?

In total we get this:

$pattern = '/(?:EUR|[$])\s*\d+(?:\.\d{2})?/';
if (preg_match($pattern, $string, $matches)) {
    echo $matches[0];
}

Upvotes: 5

Bora
Bora

Reputation: 10717

Try this one

$str = "$300.00 asking price";
preg_match('/^([\$]|EUR|€)\s*([0-9,\s]*\.?[0-9]{0,2})?+/', $str, $regs);

Outputs

array (size=3)
  0 => string '$300.00' (length=7)
  1 => string '$' (length=1)
  2 => string '300.00' (length=6)

array (size=3)
  0 => string 'EUR 300.00' (length=10)
  1 => string 'EUR' (length=3)
  2 => string '300.00' (length=6)

Upvotes: 1

Related Questions