How to capitalize the first letter of each word?

Asked

Viewed 10,471 times

7

I would like to manipulate the way the person type their name when registering, to get only the first letter of their name in the upper box. The examples I found don’t do exactly what I need.

In my case, if the person type:

  • joão Adão
  • JOHN ADAM

Must be converted to John Adam. The ucwords() PHP loses accents when saving to database.

  • http://php.net/manual/en/function.ucfirst.php look at my friend

  • 4

    And if it’s José da Silva?

  • @Bacco, sorry, but laughs a lot here.

4 answers

14

That one response from the OSen suggests the use of function mb_convert_case(). The first argument is the string to be converted, the second the mode respectively all uppercase, all lowercase and uppercase initials (MB_CASE_UPPER, MB_CASE_LOWER, and MB_CASE_TITLE) and the latter the codification.

header('Content-Type: text/html; charset=utf-8');
$str = "isso é um teste í ã ó ç";
echo mb_convert_case($str, MB_CASE_TITLE, 'UTF-8');

Phpfiddle

  • 2

    It is worth noting that the function works well to the letter even. If the name string contains any connective that must be kept de-capitalised (from, do, da, and, von, van, etc.) as well as parts that must be kept capitalized (Fulanod and Tal III, for example) it will be necessary to work a little more.

4

1

Use this function I created

function maiuscula($string) {
        $string = mb_strtolower(trim(preg_replace("/\s+/", " ", $string)));//transformo em minuscula toda a sentença
        $palavras = explode(" ", $string);//explodo a sentença em um array
        $t =  count($palavras);//conto a quantidade de elementos do array
        for ($i=0; $i <$t; $i++){ //entro em um for limitando pela quantidade de elementos do array
            $retorno[$i] = ucfirst($palavras[$i]);//altero a primeira letra de cada palavra para maiuscula
                if($retorno[$i] == "Dos" || $retorno[$i] == "De" || $retorno[$i] == "Do" || $retorno[$i] == "Da" || $retorno[$i] == "E" || $retorno[$i] == "Das"):
                    $retorno[$i] = mb_strtolower($retorno[$i]);//converto em minuscula o elemento do array que contenha preposição de nome próprio
                endif;  
        }
        return implode(" ", $retorno);
}

-4

You can do it using Javascript... this way:

<script type="text/javascript" language="Javascript">

function capitalize(campoFormulario) {
	
	var string = document.getElementById(campoFormulario).value;
	
	if(string.length > 0) {
	
		string = string.toLowerCase();
		string = string.split(' ');
		
        for (var i = 0, len = string.length; i < len; i++) {
			
			if(string[i].length > 2) {
				
				string[i] = string[i].charAt(0).toUpperCase() + string[i].slice(1);
				
			};
			
        };
		
		document.getElementById(campoFormulario).value = string.join(' ');
		return true;
		
	}
	
}

</script>

In html, in the Input field identified with id, it will look like this:

<input type="text" name="campo_nome" id="campo_id" onkeyup="capitalize(this.id);">

A single remark: when I put in the javascritp code "if(string[i].length > 2)" I am indicating that I want to capitalize only words that have more than 2 characters... if you prefer change this value, or delete this if.

  • 5

    But the question tag is php.

  • ola Diego... I believe it is impossible to manipulate the value when typing in php... since this would only happen when sending the form... even in css it would be possible to control the display of the input... however, when sending the form, the text would

Browser other questions tagged

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