Mis*_*cha 217
你可以使用这个功能:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
Run Code Online (Sandbox Code Playgroud)
ric*_*cka 29
另一个1-liner但没有preg:
$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';
echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer
Run Code Online (Sandbox Code Playgroud)
小智 25
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result); //output: this is my world, not my farm
Run Code Online (Sandbox Code Playgroud)
Joh*_*son 10
下面相当紧凑的解决方案使用PCRE正向前瞻断言来匹配感兴趣的子字符串的最后一次出现,即子字符串的出现,后面没有任何其他出现的相同子字符串.因此,该示例替换了last 'fox'with 'dog'.
$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
The quick brown fox, fox, fox jumps over the lazy dog!!!
Run Code Online (Sandbox Code Playgroud)
小智 8
你可以这样做:
$str = 'Hello world';
$str = rtrim($str, 'world') . 'John';
Run Code Online (Sandbox Code Playgroud)
结果是'你好约翰';
问候
这也将起作用:
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}
Run Code Online (Sandbox Code Playgroud)
更新稍微简洁的版本(http://ideone.com/B8i4o):
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
Run Code Online (Sandbox Code Playgroud)
只需一行代码(迟来的答案,但值得添加):
$string = 'The quick brown fox jumps over the lazy dog';
$find_me = 'dog';
preg_replace('/'. $find_me .'$/', '', $string);
Run Code Online (Sandbox Code Playgroud)
结尾的$表示字符串的结尾。
这是一个古老的问题,但为什么每个人都忽略了最简单的基于正则表达式的解决方案?正常的正则表达式量词是贪婪的,伙计们!如果你想找到一个模式的最后一个实例,只需坚持.*在它前面。就是这样:
$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);
Run Code Online (Sandbox Code Playgroud)
这会将“fox”的最后一个实例替换为“DUCK”,就像它应该的那样,并打印:
$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);
Run Code Online (Sandbox Code Playgroud)