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

Leave a Comment

Your email address will not be published. Required fields are marked *