Jump to content

Just another regex problem...


Vettel

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/214651-just-another-regex-problem/
Share on other sites

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;

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.