Capitalize string with accented characters

Asked

Viewed 2,550 times

2

I have a problem saving words with accents in MYSQL.

My bank is all set in ut8_unicode_ci and on my php pages <meta charset="utf-8">.

This solved my initial problem with accents, but I wanted the data to be saved in the database only with the first letter of each uppercase word.

I found the function ucwords() that solved my problem, the system user could type the whole customer name in high box that the system saved the way I wanted in the bank.

The problem is that if there are accents in the name it saves only the last letter before the accent. Ex: If the name is João da silva it saves only Jo. I would like some help with this because I have been researching for some time and I still can’t solve it. Below is an excerpt of the code:

function InsereMensalista()
{
    //TRAS AS VARIÁVEIS PARA O ESCOPO DA FUNÇÃO.
    global $conn, $nome, $email, $cpf, $rg, $tel, $celular, $celular2, $estado, $endereco, $bairro, $cidade, $placa1, $modelo1, $placa2, $modelo2, $mensalidade;

    //MUDA AS VARIÁVEIS PARA MINÚSCULO.
    $nome = strtolower($nome);
    $endereco = strtolower($endereco);
    $bairro = strtolower($bairro);
    $cidade = strtolower($cidade);
    $modelo1 = strtolower($modelo1);
    $modelo2 = strtolower($modelo2);

    // MUDA AS VARIÁVEIS COLOCANDO A PRIMEIRA LETRA DE CADA PALAVRA EM MAIÚsCULO ANTES DE INSERIR NO BANCO DE DADOS.
    $nome = ucwords($nome);
    $endereco = ucwords($endereco);
    $bairro = ucwords($bairro);
    $cidade = ucwords($cidade);
    $modelo1 = ucwords($modelo1);
    $modelo2 = ucwords($modelo2);

    //QUERY PARA INSERIR DADOS DIGITADOS NO FORMULÁRIO NO BANCO DE DADOS.
    $sql = "INSERT INTO mensalistas (id, nome, email, cpf, rg, telefone, celular, celular2, endereco, bairro, cidade, estado, placa1, modelo1, placa2, modelo2, mensalidade) 
    VALUES ('','$nome','$email','$cpf','$rg','$tel','$celular','$celular2','$endereco','$bairro','$cidade','$estado','$placa1','$modelo1','$placa2','$modelo2','$mensalidade')";

    //TENTA INSERIR OS DADOS NO BANCO DE DADOS.
    if($result = $conn->query($sql))
    {
        //EXIBE UM AVISO DE QUE O CADASTRO FOI EFETUADO COM SUCESSO.
        echo "<script type='text/javascript'>
        alert('Cadastro efetuado com sucesso!');
        location.href='cadastro_mensalista.php';
        </script> ";
    }
    else
    {
        //EXIBE UM AVISO DE QUE O USUÁRIO TENTOU INSERIR DADOS JÁ REGISTRADOS NO BANCO DE DADOS.
        echo "<script type='text/javascript'>
        alert('Você tentou inserir dados já cadastrados. Verifique os dados do cliente e tente novamente!');
        location.href='javascript:window.history.go(-1)';
        </script> ";
    }
}
  • Have you tried the mysqli_real_escape_string ?

  • 2

    The problem is with ucwords I believe. What the mysqli_real_escape_string influence?

  • @Weverton, by my tests and very likely that is not the ucwords that cause your problem, see the test: https://ideone.com/XfjzKQ you already tried to print part of your code to see where the information is lost ?

  • So I’m testing here I realized that the problem is in strtolower(). Only with the ucwords he recorded normal, I entered the data: "John, John, John, John, John, John" and he recorded in mysql this: John, John, John, John, John, John, John" Or put the first letter capitalized correctly, the problem is that I did not want him to save the whole name in high box. If the user type "JOÃO" he would have to save "João", for that I used strtolower(), and then he saves only "Jo".

  • Take a look at this api as well: https://market.mashape.com/semantics/accentwords

1 answer

8


ucwords() is one of php’s string manipulation functions that does not support multibyte so it cannot convert accented characters or other languages.

For each function that handles string there is a copy that works with multibyte characters, these functions have the prefix mb.

To capitalize your string use the function mb_convert_case and provide the second argument as MB_CASE_TITLE other options are MB_CASE_UPPER and MB_CASE_LOWER

<?php 

$str = 'teste éverdade bla bla óooo ýabc';
echo mb_convert_case($str,  MB_CASE_TITLE);
echo ucwords($str);

Exit:

Teste Éverdade Bla Bla Óooo Ýabc
Teste éverdade Bla Bla óooo ýabc
  • I tried but it didn’t work, I put another answer for you to see. Thank you.

  • Cara based on his answer I decided to research on the function mb_strtolower and managed to solve my problem. $name = mb_strtolower($name,'UTF-8').

  • @Wevertonjunior why convert to minuscule?

  • 2

    @rray, if he has problems, the only thing you need to do is pass the third parameter, which is the encoding. So: mb_convert_case($str, MB_CASE_TITLE, 'utf-8')

  • +1 This function is used internally by Laravel in the method Str::title

  • @rray I need to convert to tiny because I do not want you to save in the bank everything in high box. Only with ucwords if the user type the customer’s name: JOÃO SILVA I need to save in the bank always João Silva. The function ucwords worked well changing "joão silva" to "João Silva" but if the user typed everything in high box the problem occurred just when using strtolower() in words with accent, and the BD saved only "Jo". But following your explanation of the mb_ functions I got this result that solved my problem: $name = ucwords(mb_strtolower($name,'UTF-8')); Thanks again.

  • 1

    So far I don’t understand why you want to use ucwords, since you already have mb_convert_case. It’s unnecessary to do that, @Wevertonjúnior. This function @rray said has to work properly, or else there is a communication error

  • @Wevertonjunior is only to use mb_convert_case, do not need mb_strlower, do a simple test, echo mb_convert_case('AÇÃO', MB_CASE_TITLE);

  • So @rray, I put the way you said (copied and pasted) and he showed on screen "A?? No and when I put $name = mb_convert_case('ACTION', MB_CASE_TITLE) he wrote only A in the BD. But I’m not sure why otherwise: $name = ucwords(mb_strtolower($name,'UTF-8')); Worked perfectly.

  • @Wevertonjúnior, it may be the outgoing of your file, it must be as utf-8

Show 5 more comments

Browser other questions tagged

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