猿问

PHP替换字符串中最后一次出现的字符串?

有谁知道用一个字符串中的另一个字符串替换最后一个出现的字符串的快速方法?



达令说
浏览 779回答 3
3回答

慕桂英4014372

您可以使用此功能:function str_lreplace($search, $replace, $subject){    $pos = strrpos($subject, $search);    if($pos !== false)    {        $subject = substr_replace($subject, $replace, $pos, strlen($search));    }    return $subject;}

慕容森

另一种1-liner但没有预浸料:$subject = 'bourbon, scotch, beer';$search = ',';$replace = ', and';echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer

繁星coding

$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
随时随地看视频慕课网APP
我要回答