bear
bear

Reputation: 11625

Replacing text with PHP

I've got an array in PHP:

$wxCode = array(
    'VC' => 'nearby',
    'MI' => 'shallow',
    'PR' => 'partial',
    'BC' => 'patches of',
    'DR' => 'low drifting',
    'BL' => 'blowing',
    'SH' => 'showers',
    'TS' => 'thunderstorm',
    'FZ' => 'freezing',
    'DZ' => 'drizzle',
    'RA' => 'rain',
    'SN' => 'snow',
    'SG' => 'snow grains',
    'IC' => 'ice crystals',
    'PE' => 'ice pellets',
    'GR' => 'hail',
    'GS' => 'small hail',  // and/or snow pellets
    'UP' => 'unknown',
    'BR' => 'mist',
    'FG' => 'fog',
    'FU' => 'smoke',
    'VA' => 'volcanic ash',
    'DU' => 'widespread dust',
    'SA' => 'sand',
    'HZ' => 'haze',
    'PY' => 'spray',
    'PO' => 'well-developed dust/sand whirls',
    'SQ' => 'squalls',
    'FC' => 'funnel cloud, tornado, or waterspout',
    'SS' => 'sandstorm/duststorm');

and I've got a little if here:

    if (substr($part,0,1) == '-') {
        $prefix = 'light ';
        $part = substr($part,1);
    }
    elseif (substr($part,0,1) == '+') {
        $prefix = 'heavy ';
        $part = substr($part,1);
    }
    else $prefix = '';

However, I want to write a function that with turn the following string: -RA into the following text, based on the array and the if: light rain.

How would I do this?

Upvotes: 0

Views: 62

Answers (2)

koalabruder
koalabruder

Reputation: 2904

$str = str_replace(array('-', '+'), array('light ', 'heavy '), $str);
$str = str_replace(array_keys($wxCode), array_values($wxCode), $str);

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173652

You're almost there actually. Just use $part as the key to your $wxCode array:

$wxCode[$part]

If you don't have a prefix or:

$wxCode[substr($part, 1)]

If you do. You may need to use strtoupper() to make sure the two-letter code is all caps

Upvotes: 2

Related Questions