有没有人知道一种非常快速的方法,可以用字符串中的另一个字符串替换最后一个字符串?
注意,字符串的最后一个匹配项可能不是字符串中的最后一个字符。
示例:
$search = 'The';
$replace = 'A';
$subject = 'The Quick Brown Fox Jumps Over The Lazy Dog';
预期输出:
The Quick Brown Fox Jumps Over A Lazy Dog
发布于 2010-10-01 08:00:10
您可以使用此函数:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
发布于 2013-08-08 05:11:45
另一个1行代码,但不含preg:
$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';
echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer
发布于 2012-06-22 03:03:15
$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
https://stackoverflow.com/questions/3835636
复制相似问题