Blackbam Blackbam - 1 year ago 58
PHP Question

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


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
does, however it replaces any occurrence.

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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download