Summary: in this tutorial, you’ll learn how to use the PHP ucfirst() function to make the first alphabetic character uppercase.
Introduction to the PHP ucfirst() function #
The ucfirst() function accepts a string and returns a new string with the first character converted to uppercase if that character is alphabetic.
Here’s the syntax of the ucfirst() function:
ucfirst ( string $string ) : stringThe ucfirst() function use the current locale to determine which character is alphabetic.
PHP ucfirst() function example #
The following example uses the ucfirst() function to convert the first characters of the first name and last name to uppercase:
<?php
$first_name = 'john';
$last_name = 'doe'
echo ucfirst($first_name) . ' ' . ucfirst($last_name);Output:
John DoeDealing with multibyte characters #
The ucfirst() doesn’t support multibyte strings. To return a new string with the first character converted to uppercase, you can use the following mb_ucfirst() function:
<?php
function mb_ucfirst($str)
{
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}How it works.
First, get the first character of the $str using the mb_substr() function and convert it to uppercase using the mb_strtoupper() function:
mb_strtoupper(mb_substr($str, 0, 1))Then, concatenate the uppercase character with the remaining characters in the string:
mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);The following example uses the ucfirst() to convert the first letter of the string äbtissin to uppercase:
<?php
$title = 'äbtissin';
echo ucfirst($title); // doesn't workOutput:
äbtissinHowever, it doesn’t work as expected. Because in the default “C” locale characters, the ucfirst() function doesn’t convert character like umlaut-a (ä).
The following uses the mb_ucfirst() function instead:
<?php
$title = 'äbtissin';
echo mb_ucfirst($title);Output:
ÄbtissinNow, it works as expected.
Summary #
- Use the
ucfirst()function to returns a string with the first alphabetic character converted to uppercase.
Thank you for your feedback!