I have a string of currencies - currency code, name and rates (first rate is units per EUR and second is EUR per unit).
string(6429) " USD US Dollar 1,164342 0,858854
EUR Euro1,000000 1,000000 GBP British Pound 0,842392 1,187096
INR Indian Rupee 87,128927 0,011477 AUD Australian Dollar 1,549853 0,645222 CAD Canadian Dollar 1,435142 0,696795 SGD Singapore Dollar 1,564234 0,639291 CHF Swiss Franc 1,070921 0,933776 MYR Malaysian Ringgit 4,846357 0,206341 JPY Japanese Yen 132,999525 0,007519 CNY Chinese Yuan Renminbi 7,444264 0,134332 NZD New Zealand Dollar 1,616910 0,618464 THB Thai Baht 38,890927 0,025713 HUF Hungarian Forint 362,270767 0,002760 AED Emirati Dirham 4,276047 0,233861 HKD Hong Kong Dollar 9,052195 0,110470 MXN Mexican Peso 23,485298 0,042580 ZAR South African Rand 16,811235 0,059484 PHP Philippine Peso 59,132446 0,016911
and so on... IMPORTANT - This is copy/paste string so whitespace count is like in example and it can be random between integers and words. String is in one line without line breaks.
So my goal here is to get currency code and currency rate "unit per EUR" (first value)
Preferable output associative array.
Example:
$pairs = [
'USD' => 1,164342,
'GBP' => 0,842392,
];
and so on for every currency.
I can't use any API.
Can anyone help me with this task?
Update: Piece of original string with line breaks
string(6667) "Valūtas kods Valūtas nosaukums Vienības par EUR EUR par vienību
USD US Dollar 1,164342 0,858854
EUR Euro 1,000000 1,000000
GBP British Pound 0,842392 1,187096
INR Indian Rupee 87,128927 0,011477
AUD Australian Dollar 1,549853 0,645222
CAD Canadian Dollar 1,435142 0,696795
SGD Singapore Dollar 1,564234 0,639291
CHF Swiss Franc 1,070921 0,933776
MYR Malaysian Ringgit 4,846357 0,206341
JPY Japanese Yen 132,999525 0,007519
CNY Chinese Yuan
Renminbi 7,444264 0,134332
NZD New Zealand Dollar 1,616910 0,618464
CodePudding user response:
I hope this is something that you need. Check it please
$string = " USD US Dollar 1,164342 0,858854
EUR Euro1,000000 1,000000 GBP British Pound 0,842392 1,187096
INR Indian Rupee 87,128927 0,011477 AUD Australian Dollar 1,549853 0,645222 CAD Canadian Dollar 1,435142 0,696795 SGD Singapore Dollar 1,564234 0,639291 CHF Swiss Franc 1,070921 0,933776 MYR Malaysian Ringgit 4,846357 0,206341 JPY Japanese Yen 132,999525 0,007519 CNY Chinese Yuan Renminbi 7,444264 0,134332 NZD New Zealand Dollar 1,616910 0,618464 THB Thai Baht 38,890927 0,025713 HUF Hungarian Forint 362,270767 0,002760 AED Emirati Dirham 4,276047 0,233861 HKD Hong Kong Dollar 9,052195 0,110470 MXN Mexican Peso 23,485298 0,042580 ZAR South African Rand 16,811235 0,059484 PHP Philippine Peso 59,132446 0,016911 ";
preg_match_all('/(USD|GBP)[^\d]*(\d*,?\d*)/', $string, $output);
if ($output) {
var_dump(array_combine($output[1], $output[2]));
}
Just change list of currencies if you need something else like only usd and gbp will be USD|GBP and so on