PDA

View Full Version : currency conversion in a string

thedevilspride
06-06-2005, 03:56 PM
What i'm trying to do is convert all currency in a string with the approximate amount in another currency.

For example:
"You can buy this product at £12 from this company. You can also buy a similar product for £8 at this online store."

Becomes:
"You can buy this product at £12 (around \$21.80 or €17.77) from this company. You can also buy a similar product for £8 (around \$14.55 or €11.85) at this online store."

The actual conversion to different currencies is pretty easy i'm just not sure how to replace the existing ones in a string. i've been experimenting with preg_replace but found it a little confusing.

Thanks :)

marek_mar
06-06-2005, 08:32 PM
Well this can work aslong you are sue about the character you use as pounds (it's not a standard character).

<?php
\$txt = 'You can buy this product at £12.76 from this company. You can also buy a similar product for \$89.86 at this online store.';
//punds to dollars and dollars to pounds.
\$currency = array(36 => 2/*pound to dollar*/, 63 => 0.5/*dollar to pound*/); // myltiply x by value to get y ex. pund * value = dollar.
\$sign = array(36 => 63, 63 => 36); //Did'nt think of a better way...
print \$txt . "\n";
if(preg_match_all('/([\$£])([0-9]+)(?:[\.,]([0-9]{1,2}))?/', \$txt, \$match))
{
foreach(\$match[0] as \$key => \$value)
{
// \$match[1][\$key] sign \$ or pound.
// \$match[2][\$key] amount.
// \$match[2][\$key] / 100 cents.
// \$match[3][\$key] + \$match[2][\$key] / 100 full amouunt.
\$txt = str_replace(\$value, chr(\$sign[ord(\$match[1][\$key])]) . (\$match[2][\$key] + \$match[3][\$key] / 100) * \$currency[ord(\$match[1][\$key])], \$txt);
}
print \$txt;
}
else
{
print 'nothing to convert';
}
?>