Capitalize the first letter of every word in a string with PHP

Asked

Viewed 1,285 times

1

Function-based ucfirst, but instead of converting only the first letter of the first word, how to do it, using PHP, so that the first letter of all words in a string are capitalized?

Thus, following the pattern of "full name", example:

'joão silva' => 'João Silva'
'maria Silva' => 'Maria Silva'
'gustavo da silva' => 'Gustavo Da Silva'
'GUILHERME DE CAMPOS' => 'Guilherme De Campos'

1 answer

3

You can use ucwords to this end:

Capitalizes the first character of each word

The problem of using ucwords would be when the initial characters are accented, in case they would not be capitalized. I recommend the use of mb_convert_case, but if you are sure that no name starts with accent, then ucwords can handle.

// exemplo 1
$str = 'joão silva';
echo ucwords( $str );

// exemplo 2
$str = 'joão silva';
echo mb_convert_case( $str , MB_CASE_TITLE , 'UTF-8' );

The output of both is João Silva, as you can see in the example in Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.