How to replace the last occurrence of a character in a string with PHP

1 Answer

0 votes
function replaceTheLastOccurrenceOfACharacterInAString($str, $charToReplace, $replacementChar) {
    $pos = strrpos($str, $charToReplace);

    if ($pos !== false) {
        $str[$pos] = $replacementChar;
    }
    
    return $str;
}

$str = "c++ c python c++ java c++ php";
$charToReplace = 'c';
$replacementChar = 'W';

$str = replaceTheLastOccurrenceOfACharacterInAString($str, $charToReplace, $replacementChar);

echo $str;



/*
run:

c++ c python c++ java W++ php

*/

 



answered Sep 9, 2024 by avibootz

Related questions

...