While developing another WordPress plugin, I needed an equivalent of the PHP ucfirst function, but in the mb_* version (i.e., for multibyte strings). Visiting php.net, I was surprised to find that such a function doesn't exist. After digging through the internet, I found one (or maybe two) solutions on Stack Overflow.
After refining the found code, I ended up with the following result:
public function mb_ucfirst($string, $encoding = 'UTF-8')
{
$strlen = mb_strlen($string, $encoding);
$first_char = mb_substr($string, 0, 1, $encoding);
$then = mb_substr($string, 1, $strlen - 1, $encoding);
return mb_strtoupper($first_char, $encoding) . mb_strtolower($then, $encoding);
}Where:
$strlen — total length of the string, taking encoding into account (the second parameter of our function)
$first_char — the first character of the string
$then — all remaining characters (i.e., excluding the first one)
And finally, the function returns the first character converted to uppercase and all the rest to lowercase, with encoding properly handled.
