Turn the first letter of all the words of a string in upper case with PHP

1

Based on the ucfirst function, but instead of converting only the first letter of the first word, such as to do, using PHP, so that the first letter of all words in a string is converted to uppercase?

In this way, following the "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'
    
asked by anonymous 01.07.2015 / 08:19

1 answer

3

You can use ucwords for this purpose:

  

Converts the first character of each word to upper case

The problem of using ucwords would be when the initial characters are accented, in case they would not be converted to upper case. I recommend using mb_convert_case , but if you are sure that no name starts with an accent, then ucwords gives the message.

// 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 the example in Ideone .

    
01.07.2015 / 08:33