Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jul 2003
    Location
    London
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    currency conversion in a string

    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

  • #2
    Senior Coder
    Join Date
    Aug 2003
    Location
    One step ahead of you.
    Posts
    2,815
    Thanks
    0
    Thanked 3 Times in 3 Posts
    Well this can work aslong you are sue about the character you use as pounds (it's not a standard character).
    PHP Code:
    <?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 => 6363 => 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($valuechr($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';
    }
    ?>
    I'm not sure if this was any help, but I hope it didn't make you stupider.

    Experience is something you get just after you really need it.
    PHP Installation Guide Feedback welcome.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •