phpstr-replacestrtrstrrchr

strrchr with strtr or str_replace in PHP


I have searched a lot of sites and SO answers for replacing characters in strings, but I didn't find a solution.

I need to replace only the last used character 'é' of a string. It should work for every string, also if the string only contains once character 'é'.

code

echo strtr (strrchr ( 'accélérer','é' ), array ('é' => 'è'));   //  output èrer
echo str_replace("é","è",strrchr ( 'accélérer','é' ));           // output èrer

desired results

accélérer -> accélèrer

sécher-> sècher


Solution

  • Have created custom function. Might be useful:

    <?php
    $str = 'accélérer';
    $output = replaceMultiByte($str, 'é', 'è');
    echo "OUTPUT=".$output; // accélèrer
    echo '<br/><br/>';
    
    $str = 'sécher';
    $output = replaceMultiByte($str, 'é', 'è');
    echo "OUTPUT=".$output; // sècher
    
    function replaceMultiByte($str, $replace, $replaceWith)
    {
        $exp = explode($replace, $str);
    
        $i = 1;
        $cnt = count($exp);
        $format_str = '';
        foreach($exp as $v)
        {
            if($i == 1)
            {
                $format_str = $v;
            }
            else if($i == $cnt)
            {
                $format_str .= $replaceWith . $v;
            }
            else
            {
                $format_str .= $replace . $v;
            }
            $i++;
        }
        return $format_str;
    }
    ?>