Hi, 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 every "s" in a string how can I do that in PHP?
Hi, 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 every "s" in a string how can I do that in PHP?
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.
$result = rtrim($str, 's');
$result = str_pad($result, strlen($str) - 1, 's');
See rtrim()
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