Jump to content

Help with simple regex


smith.james0

Recommended Posts

What are you trying to replace it with? Do you just want to replace the km/h or do you need to first get the number to convert it to a different unit? If you need to do the latter, you will need to do a preg_match() to get the number and then a preg_replace to replace the number and the unit measurement.

$subject = 'ds WSW 16km/h. Humidity will be 97% with . . .';

//Check if string contains ##km/h
if(preg_match("#(\d*)km/h#is", $subject, $match))
{
    //Extract kilos
    $kmUnits = $match[1];
    //Convert to miles
    $mileUnits = round($kmUnits * .6214);
    //Replace kilo reference with miles
    $subject = preg_replace("#\d*km/h#is", "{$mileUnits}mph", $subject);
}

echo $subject;

Output: ds WSW 10mph. Humidity will be 97% with . . .

 

Note: This only works if the subject has one such reference. If there can be multiple such references in the same text, then you would need to modify the above.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.