Separate currency and amount from line

I am importing a file that has a sum with different currencies

£12.10 $26.13 €12.50 

I need to import and convert this into a single currency. I split the line as follows

 $parts = split(' ', preg_replace("/([0-9])/", ' ${1}', $amount, 1)); 

Failed to get preg_split to work with PREG_SPLIT_DELIM_CAPTURE

 $parts = preg_split("/\d/", $amount, 2, PREG_SPLIT_DELIM_CAPTURE); 

I have a currency sign for a currency code

 $currencySymbols = array('£'=>'GBP', '$'=>'USD','€'=>'EUR') 

I need 1. divide the line by the currency sign and the value - if there is a better way, then what am I doing 2. Translate the currency sign into the currency code. Failed to map to $ currencySymbols [$ parts [0]]

Any help would be appreciated. (PHP 5.2.6) using charset = utf-8

Many thanks

+3
source share
2 answers

You cannot use splitting, but matching patterns to determine the amount and currency used. Because in some locales the currency symbol appears before the sum, in others - by the sum. In addition, in some locales, the symbol and number are separated by spaces.

You can use the following function:

  function findAmountAndCurrency($s, &$amount, &$currency){ $re_amount="/[0-9\.]+/"; $re_curr="/[£\$€]+/"; preg_match($re_amount, $s, $matches); $amount = floatval($matches[0]); preg_match($re_curr, $s, $matches); $currency = $matches[0]; } 

Here's how it will be used:

  function handle($s){ $currencySymbols = array('£'=>'GBP', '$'=>'USD','€'=>'EUR'); findAmountAndCurrency($s, $amount, $currency); echo("Amount: " . $amount . "<br/>"); echo("Currency: " . $currency . "<br/>"); echo("Identified Currency: " . $currencySymbols[$currency] . "<br/>"); } handle("£12.10"); handle("3.212 €"); handle("$ 99.99"); 

You may have a problem with the EURO sign if you have a UTF-8 input. It is not possible to verify the solution right now. Maybe someone else can help.

+3
source

All Articles