PHP在string中replace最后一次出现的string?

任何人都知道一个非常快速的方法来replacestring中的另一个string的最后一次出现的string?

你可以使用这个function:

 function str_lreplace($search, $replace, $subject) { $pos = strrpos($subject, $search); if($pos !== false) { $subject = substr_replace($subject, $replace, $pos, strlen($search)); } return $subject; } 

另一个class轮,但没有preg:

 $subject = 'bourbon, scotch, beer'; $search = ','; $replace = ', and'; echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer 
 $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 

你可以这样做:

 $str = 'Hello world'; $str = rtrim($str, 'world') . 'John'; 

结果是'Hello John';

问候

以下相当紧凑的解决scheme使用PCRE正向超前断言来匹配最后一次出现的感兴趣子string,即出现的子string不会出现任何其他出现的相同子string。 因此,这个例子用'dog'代替了last 'fox' 'dog'

 $string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!'; echo preg_replace('/(fox(?=.*fox.*))/', 'dog', $string); 

OUTPUT:

 The quick brown fox, fox, fox jumps over the lazy dog!!! 

这也将工作:

 function str_lreplace($search, $replace, $subject) { return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1); } 

更新稍微更简洁的版本( http://ideone.com/B8i4o ):

 function str_lreplace($search, $replace, $subject) { return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1); } 

只需一行代码(迟交,但值得添加):

 $string = 'The quick brown fox jumps over the lazy dog'; $find_me = 'dog'; preg_replace('/'. $find_me .'$/', '', $string); 

结尾$表示string的结尾。

 $string = "picture_0007_value"; $findChar =strrpos($string,"_"); if($findChar !== FALSE) { $string[$findChar]="."; } echo $string; 

除了代码中的错误之外,Faruk Unal也是最好的select。 一个function是诀窍。

在regexpression式中使用“$”来匹配string的末尾

 $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' 

您可以使用strrpos()来查找最后一个匹配项。

 $string = "picture_0007_value"; $findChar =strrpos($string,"_"); echo $string[$MyURL]="."; echo $string; 

输出:picture_0007.value