smith.james0 Posted December 27, 2013 Share Posted December 27, 2013 I have the following string ds WSW 16km/h. Humidity will be 97% with…. I would like to get the 16km/h to replace it. This is my first time writing regex and after a bit of reading I thought this might work, (\S+)km/h\s but it doesn't Can anyone help? James Quote Link to comment https://forums.phpfreaks.com/topic/284930-help-with-simple-regex/ Share on other sites More sharing options...
.josh Posted December 27, 2013 Share Posted December 27, 2013 preg_match('~\b\d+km/h\b~',$string,$match); Quote Link to comment https://forums.phpfreaks.com/topic/284930-help-with-simple-regex/#findComment-1463114 Share on other sites More sharing options...
Psycho Posted December 27, 2013 Share Posted December 27, 2013 (edited) 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 December 27, 2013 by Psycho Quote Link to comment https://forums.phpfreaks.com/topic/284930-help-with-simple-regex/#findComment-1463116 Share on other sites More sharing options...
smith.james0 Posted December 27, 2013 Author Share Posted December 27, 2013 hmmm my expression was really wrong thanks Psycho for the extra bit of code, could you explain how I would go about changing multiple references? James Quote Link to comment https://forums.phpfreaks.com/topic/284930-help-with-simple-regex/#findComment-1463124 Share on other sites More sharing options...
Solution .josh Posted December 27, 2013 Solution Share Posted December 27, 2013 $subject = 'ds WSW 16km/h. Humidity will be 97% with 28km/h. . .'; $subject = preg_replace_callback( '~\b(\d+)km/h\b~i', function($m){return round($m[1]*.6214).'mph';}, $subject ); Quote Link to comment https://forums.phpfreaks.com/topic/284930-help-with-simple-regex/#findComment-1463125 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.