str*_*ade 10 php string replace
我需要知道如何用""替换字符串中的最后一个"s"
假设我有一个类似测试人员的字符串,输出应该是测试人员.它应该只替换字符串中的最后一个"s"而不是每个"s"如何在PHP中执行此操作?
zer*_*kms 20
if (substr($str, -1) == 's')
{
$str = substr($str, 0, -1);
}
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 16
更新:没有使用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
Run Code Online (Sandbox Code Playgroud)
strrpos
返回字符串最后一次出现的索引,并substr_replace
替换从某个位置开始的字符串.
(就像我刚刚注意到的那样,这与戈登提出的相同.)
到目前为止,所有答案都删除了单词的最后一个字符.但是,如果你真的想替换最后一次出现的字符,你可以使用preg_replace
一个负前瞻:
$s = "A sentence with 'Testers' in it";
echo preg_replace("%s(?!.*s.*)%", "", $string );
// Ouputs: A sentence with 'Tester' in it
Run Code Online (Sandbox Code Playgroud)
您的问题有点不清楚是否要删除s
字符串的末尾或字符串中的最后一次出现s
.这是一个区别.如果您想要第一个,请使用zerkms提供的解决方案.
此函数删除from 的最后一次出现,无论它在字符串中的位置如何,或者在字符串中没有出现$ char时返回整个字符串.$char
$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"
Run Code Online (Sandbox Code Playgroud)
如果你的目的是为了变形,例如单调/复数单词,那么看看这个简单的变形器类来知道要采取的路线.
$result = rtrim($str, 's');
$result = str_pad($result, strlen($str) - 1, 's');
Run Code Online (Sandbox Code Playgroud)