Jump to content

Help with simple regex


smith.james0
Go to solution Solved by .josh,

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.

Edited by Psycho
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.