How to convert the first letter of each word to upper case?

6

I would like to manipulate the way the person types the name when registering, to be left with only the first letter of the name in the upper case. The examples I found do not do exactly what I need.

In my case, if the person types:

  • joão adão
  • JOHN ADAM

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

    
asked by anonymous 10.09.2014 / 15:22

3 answers

11

This SO response en suggests using the mb_convert_case() . The first argument is the string to be converted, the second is the case respectively all uppercase, all lowercase and uppercase ( MB_CASE_UPPER , MB_CASE_LOWER , and MB_CASE_TITLE ) and last the encoding.

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

PHPFiddle

    
10.09.2014 / 15:34
3
$str = 'LOREM IPSUM';

echo mb_convert_case($str, MB_CASE_TITLE, "UTF-8");

link

    
10.09.2014 / 15:33
-1

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

<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 field Input identified with the id, it will look like this:

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

One 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, , or delete that if.

    
04.06.2017 / 20:49