Jump to content

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;

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.