.Maui Blog

PHP – Replace last occurrence in a String

<?php
function str_lreplace($search, $replace, $subject) {
    $pos = strrpos($subject, $search);

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

    return $subject;
}

$search = ".Maui";
$replace = "is awesome";
$subject = ".Maui .Maui";

echo str_lreplace($search, $replace, $subject);
//Result: .Maui is awesome
Exit mobile version