简体   繁体   中英

Automatically convert currencies and metrics from a text in PHP

I have a text like this

$text="The tower is 94.5m high, 
       the view is up to 100km. 
       The entrance is 8€";

Now I want to provide the tooltip for each metrics or currencies to get the result like this:

$text="The tower is <abbr title="310ft">94.5m</a> high, 
       the view is up to <abbr title="62mi">100km</abbr>. 
       The entrance is <abbr title="10USD">8€</abbr>

Some nice PHP function to convert these numbers automatically within the text? Thanks.

edit

To make this example simple, let's suppose we have fix rates everywhere. The question is, what kind of preg_replace or whatever to use... I used only something like this

preg_replace("/(.*)€/", $1*1.2, $text)

that is just an example how I was expecting to make it work, but of course it is not. :)

There's no built-in PHP function that will automatically do conversion between different unit types. You'll have to do it yourself with the appropriate conversion rates.

You need to write your own functions to do this. You do this in PHP like the following:

function meters_in_feet($meters)
{
    return $meters*3.28; // source: Google
}

Then you need to call it like:

$height_meters = 94.5;
$height_feet = meters_in_feet($height_meters);

Then:

echo '<abbr title="'.$height_feet.'">'.$height_meters.'m</a> high.';

This smells like a homework question, though, so as for getting the measurements etc out of an input text string which is probably what you're being asked to do, that's an exercise for the reader. ;)

Something like the following:

$text="The tower is 94.5m high,  
       the view is up to 100km.  
       The entrance is 8€";

$result = preg_replace_callback("/(([0-9\.]+)(k?m))/", 'fn', $text);

var_dump($result);

function fn($matches) {
    switch($matches[3]) {
        case 'm' :
            // m to feet
            $conversion = $matches[2] * 3.28;
            $conversionUOM = 'ft';
            break;
        case 'km' :
            // km to miles
            $conversion = $matches[2] * 0.6;
            $conversionUOM = 'miles';
            break;
    }
    return '<abbr title="'.$conversion.$conversionUOM.'">'.$matches[0].'</abbr>';
}

You'll need to adjust the regexp and write additional cases for any other UOM conversion units you're likely to need, and use the correct figures in the actual conversions (I just used quick and dirty values), and any formatting of the numbers too... but it should give you the basis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM