Answers:
您可以使用此功能:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
strpos — Find the position of the first occurrence of a substring in a string
-编辑:哇。php天才们真的做了一个叫做strpos
and 的函数strrpos
。谢谢....
$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
以下相当紧凑的解决方案使用PCRE正向超前断言来匹配目标子字符串的最后一次出现,即该子字符串的出现,然后再出现同一子字符串的任何其他出现。因此,例如将替换last 'fox'
用'dog'
。
$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);
输出:
The quick brown fox, fox, fox jumps over the lazy dog!!!
$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!'; echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);
您可以这样做:
$str = 'Hello world';
$str = rtrim($str, 'world') . 'John';
结果是“你好约翰”;
问候
这也将起作用:
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}
UPDATE稍微简洁一些的版本(http://ideone.com/B8i4o):
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
这是一个古老的问题,但是为什么每个人都忽略了最简单的基于正则表达式的解决方案?普通的正则表达式量词是贪婪的,人们!如果要查找某个模式的最后一个实例,只需坚持.*
在它的前面。这是如何做:
$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);
它将像预期的那样将“ fox” 的最后一个实例替换为“ DUCK”,并打印:
The quick brown fox, fox, fox, DUCK, jumps over etc.
在正则表达式上使用“ $”以匹配字符串的结尾
$string = 'The quick brown fox jumps over the lazy fox';
echo preg_replace('/fox$/', 'dog', $string);
//output
'The quick brown fox jumps over the lazy dog'
感兴趣的人:我编写了一个使用preg_match的函数,以便您可以使用regex从右侧替换。
function preg_rreplace($search, $replace, $subject) {
preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
$lastMatch = end($matches);
if ($lastMatch && false !== $pos = strrpos($subject, $lastMatchedStr = $lastMatch[0])) {
$subject = substr_replace($subject, $replace, $pos, strlen($lastMatchedStr));
}
return $subject;
}
或作为两种选择的简化组合/实现:
function str_rreplace($search, $replace, $subject) {
return (false !== $pos = strrpos($subject, $search)) ?
substr_replace($subject, $replace, $pos, strlen($search)) : $subject;
}
function preg_rreplace($search, $replace, $subject) {
preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
return ($lastMatch = end($matches)) ? str_rreplace($lastMatch[0], $replace, $subject) : $subject;
}
基于https://stackoverflow.com/a/3835653/3017716和https://stackoverflow.com/a/23343396/3017716
s($str)->replaceLast($search, $replace)
如在该独立库中所发现的,您可能会有所帮助。