感兴趣的人:我编写了一个利用 preg_match 的函数,以便您可以使用正则表达式从右侧替换。
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