Show surname and rest of the name

I have a database with customer names, and I want to separate the last name from the rest of the name.

In the name Diana Margarida Paulino Maria

If I use:

$str = "Diana Margarida Paulino Maria";

// Get Frist and Last Word
   $array = explode(" ",$str);

   $first_word = $array[0];

   $last_word  = $array[count($array)-1];

   echo $first_word. ', '.$last_word;

It’s every thin ok, anda show Diana as first_word and Maria as last_word

Even is I use:

    function getLastWord($string)
    {
        $string = explode(' ', $string);
        $last_word = array_pop($string);
        return $last_word;
    }

Or this

  $words = explode( " ", $str );
array_splice( $words, -1 );
echo implode( " ", $words );

In this case show name without surname

The problem is that if you return a php msqyl select query from that name and use these functions, the nickname never appears

I’ve tried directly through the mysql query itself

SELECT substring_index(nome, ' ', 1) as first, substring_index(nome, ' ', -1) as last

And in the specific case of this name (and some others – Leandro Monteiro Rodrigues Figueiredo; Pedro António Duarte Lopes) the nickname still does not appear

I used the above codes with many other names and in almost all situations the nickname is indicated correctly

In the mysql database the name field is encoded with utf8_general_ci

Either way it’s weird because I can’t find a pattern for the error