开发者

How to replace the Last "s" with "" in PHP

I need to know how I can replace the last "s" from a string with ""

Let's say I have a string like testers and the output should be tester. It should just replace the last "s" and not eve开发者_C百科ry "s" in a string how can I do that in PHP?


if (substr($str, -1) == 's')
{
    $str = substr($str, 0, -1);
}


Update: Ok it is also possible without regular expressions using strrpos ans substr_replace:

$str = "A sentence with 'Testers' in it";
echo substr_replace($str,'', strrpos($str, 's'), 1);
// Ouputs: A sentence with 'Tester' in it

strrpos returns the index of the last occurrence of a string and substr_replace replaces a string starting from a certain position.

(Which is the same as Gordon proposed as I just noticed.)


All answers so far remove the last character of a word. However if you really want to replace the last occurrence of a character, you can use preg_replace with a negative lookahead:

$s = "A sentence with 'Testers' in it";
echo preg_replace("%s(?!.*s.*)%", "", $string );

// Ouputs: A sentence with 'Tester' in it


$result = rtrim($str, 's');
$result = str_pad($result, strlen($str) - 1, 's');

See rtrim()


Your question is somewhat unclear whether you want to remove the s from the end of the string or the last occurence of s in the string. It's a difference. If you want the first, use the solution offered by zerkms.

This function removes the last occurence of $char from $string, regardless of it's position in the string or returns the whole string, when $char does not occur in the string.

function removeLastOccurenceOfChar($char, $string)
{
    if( ($pos = strrpos($string, $char)) !== FALSE) {
        return substr_replace($string, '', $pos, 1);
    }
    return $string;
}
echo removeLastOccurenceOfChar('s', "the world's greatest");
// gives "the world's greatet"

If your intention is to inflect, e.g singularize/pluralize words, then have a look at this simple inflector class to know which route to take.


$str = preg_replace("/s$/i","",rtrim($str));


The very simplest solution is using rtrim()

That is exactly what that function is intended to be used for: Strip whitespace (or other characters) from the end of a string.

Nothing simpler than that, I am not sure why, and would not follow the suggestions in this thread going from regex to "if/else" blocks.

This is your code:

$string = "Testers";
$stripped = rtrim( $string, 's' );

The output will be: Tester

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜