Its own mb_ucfirst function in PHP

Its own mb_ucfirst function in PHP

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.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

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