Blackbam Blackbam - 6 months ago 20
PHP Question

PHP: Efficient/simple way to replace every occurrence but the last occurence of a substring in a string (str_replace_except_last)?

Imagine the following inputs and the desired output after str_replace_except_last($replace_except_last,$replacement,$text):

func(".","",12.833331.3198912.980289012.92) => 128333313198912980289012.92
func(".","",31.0) => 31.0
func(".","",8) => 8
func(".","",9190.1.1.1....1.1.....1) => 919011111.1
func(".","",98909090....) => 98909090.
func("beer","","My beer is the best beer.") => My is the best beer.
func("it","fit,"Is it really it or is it not?") => Is fit really fit or is it not?

Want to perform the simple task of removing every occurrence of a character or substring but NOT the last occurrence. Basically this is what str_replace does however it replaces any occurrence.

Hint: Made some experiments with substr_count however I did not find how to replace ocurrence number X in a string easily?


I think this will be the most efficient/simple solution (however I didn't run it though some run-time test).

function str_replace_except_last($needle, $replace, $text) {
    if ($last_pos = strrpos($text, $needle)) {
        $text = str_replace($needle, $replace, substr($text, 0, $last_pos)) . substr($text, $last_pos);
    return $text;