Skip to content
Advertisement

How to convert all characters to uppercase, except for the last character in PHP

I need to convert all characters to uppercase except for the last character in the following string:

<?php
    $str = "Hello";

    echo $_str = mb_strtoupper(mb_substr($str, 0, strtolower($str))); 
    ?>

Advertisement

Answer

Divide the string into the relevant parts, treat them accordingly, and then rejoin.

$str = "Hello";
$parts = mb_str_split($str, mb_strlen($str) - 1);
$out = mb_strtoupper($parts[0]) . mb_strtolower($parts[1]);

var_dump($out);

Output:

string(5) "HELLo"
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement