Vettel Posted September 28, 2010 Share Posted September 28, 2010 I have the following string: $str = +15.865s I need to use preg_replace() to remove the 's' from the end of the string. However 's' should only be removed if it is immediately preceded by a number. I started with the following code, but obviously it also removed the number that comes before the 's'. $new = preg_replace('/[0-9]s/', '', $str); How do remove the 's' but keep the number? Also I can't use str_replace(), just in case it's suggested. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/214651-just-another-regex-problem/ Share on other sites More sharing options...
gizmola Posted September 28, 2010 Share Posted September 28, 2010 It is always faster if you can use simple string functions instead of regex. In this case you can use substr combined with is_numeric. $str = '+15.865s'; $str = (is_numeric(substr($str, -2, 1)) && (substr($str, -1) == 's')) ? substr($str, 0, -1) : $str; echo $str; $str = '+15.865Rs'; $str = (is_numeric(substr($str, -2, 1)) && (substr($str, -1) == 's')) ? substr($str, 0, -1) : $str; echo $str; Quote Link to comment https://forums.phpfreaks.com/topic/214651-just-another-regex-problem/#findComment-1116878 Share on other sites More sharing options...
Vettel Posted September 28, 2010 Author Share Posted September 28, 2010 Thanks Gizmola. Your solution certainly works, but having it in the form of a preg_replace() function would make it a lot easier for me to implement. Do you, or anyone else, have any other ideas? Quote Link to comment https://forums.phpfreaks.com/topic/214651-just-another-regex-problem/#findComment-1116891 Share on other sites More sharing options...
.josh Posted September 28, 2010 Share Posted September 28, 2010 $new = preg_replace('/([0-9])s/', '$1', $str); Quote Link to comment https://forums.phpfreaks.com/topic/214651-just-another-regex-problem/#findComment-1116913 Share on other sites More sharing options...
Vettel Posted September 29, 2010 Author Share Posted September 29, 2010 Thanks Crayon Violet- just what I was looking for Quote Link to comment https://forums.phpfreaks.com/topic/214651-just-another-regex-problem/#findComment-1116938 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.