Extract name and last mysql surname

Asked

Viewed 2,861 times

3

Good morning Everyone, how do I extract the name and last name from a record. However the same should return the name and surname when you have only one surname. My table is like this.

table = 'users';
field 1 = 'name';
campo2 = 'sobronomy';

Name: Eduardo da Silva Fernandes

I would like to extract this: 'Eduardo Fernandes';

I did it here, but it only works for the records containing 2 surnames.

$separar = explode(' ', $reg['nome'] . '. .' . $reg['sobrenome']);
            $primeiroNome = array_shift($separar);
            $ultimoNome = array_pop($separar);

1 answer

8


If you want to extract right from the database with SQL:

SELECT SUBSTRING_INDEX(coluna_nome, ' ', 1) as nome, SUBSTRING_INDEX(coluna_nome, ' ', -1) as sobrenome from tabela_pessoas;

But from what you’ve shown SQL, you don’t even go in there to do php:

$nome_todo = 'Eduardo da Silva Fernandes';
$nomes = explode(' ', $nome_todo); // separamos por espaços e fica: Array ( [0] => Eduardo [1] => da [2] => Silva [3] => Fernandes )
$nome = $nomes[0]; // primeiro nome
$sobrenome = $nomes[count($nomes) - 1]; // ultimo nome, total de nomes - 1 que é o ultimo elemento de $nomes

echo $nome; // Eduardo
echo $sobrenome; // Fernandes

However, if you want to do this for multiple users you can (and should) build a function so you are not repeating code:

function nome_sobrenome($nome_todo) {
    $nomes = explode(' ', $nome_todo);
    if(count($nomes) === 1) { // caso alguém tenha um só nome
        return $nomes[0];
    }
    return $nomes[0]. ' ' .$nomes[count($nomes) - 1];
}

$eduardo = nome_sobrenome('Eduardo da Silva Fernandes'); // Eduardo Fernandes
$maria = nome_sobrenome('Maria dos Santos Anacleto Constantina'); // Maria Constantina
$adriana = nome_sobrenome('Adriana Lima'); // Adriana Lima
$miguel = nome_sobrenome('Miguel'); // Miguel
  • Very good guy. Thanks for the help.

  • Relax, I’m glad I helped

  • Excellent tip, helped me a lot on a project here, great hug.

Browser other questions tagged

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