Shortening the names of people

Asked

Viewed 1,249 times

4

I need a script that shortens people’s names.

For example: Name: Fernando José Silva Machado

With the script he cuts the surnames and leaves only the initials and the last surname

It would look like this: Name: Fernando J. S. Machado

I have a system for registering people and generating member portfolios that picks up the name, so I would like you to listen to the names that have more than one surname, keep the last in full and the others with the initial and a point.

Someone could help me?

I found this script but it takes the first and last, unlike me who want to keep the initials in the middle.

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];
}
  • 1

    As the question is marked as pending, I cannot post the answer here. But maybe this code will help you. https://pastebin.com/SmzzefAN

  • That there little brother, exactly what I wanted. thank you very much!!!!

2 answers

2


My suggestion is to use mb_convert_case (that will support the accents) to normalize and preg_split to divide

Note: to use functions mb_ it is necessary to activate the mbstring

In php.ini remove the ; the front of (if it’s Windows):

of ;extension=php_mbstring.dll for extension=php_mbstring.dll

if it’s Linux:

of ;extension=mbstring.so for extension=mbstring.so

if it’s PHP7.2:

of ;extension=mbstring for extension=mbstring

<?php
/**
 * Encurta nomes do meio com suporte para unicode e acentos
 *
 * @param string $name        Define nome para ser encurtado
 * @param array|null $ignore  Nomes/palavras que NÃO devem ser encurtados
 * @return string $encode     Define a codificação do nome (opcional)
 */
function mb_shorten_name($name, array $ignore = null, $encode = null)
{
    $ignore = $ignore === null ? array( 'de', 'da', 'do', 'dos' ) : $ignore;

    //Converte para case-title
    if ($encode) {
        $name = mb_convert_case($name, MB_CASE_TITLE, $encode);
    } else {
        $name = mb_convert_case($name, MB_CASE_TITLE);
    }

    //Divide a string
    $names = preg_split('#\s+#', $name);

    $j = count($names);

    // caso alguém tenha um só nome
    if ($j === 1) return trim($name);

    //Acaso só tenha menos de 3 nomes
    if ($j < 3) return implode(' ', $names);

    $j--;

    $rebuild = array( $names[0] );

    for ($i = 1; $i < $j; $i++) {
        $ex = $encode ? mb_strtolower($names[$i], $encode) : mb_strtolower($names[$i]);

        if (in_array($ex, $ignore)) {
           $rebuild[] = $ex;
        } elseif ($encode) {
           $rebuild[] = mb_substr($names[$i], 0, 1, $encode) . '.';
        } else {
           $rebuild[] = mb_substr($names[$i], 0, 1) . '.';
        }
    }

    $rebuild[] = $names[$j];

    return implode(' ', $rebuild);
}

var_dump(mb_shorten_name('joão marques almeida de castro filho')); # João M. A. de C. Filho
var_dump(mb_shorten_name('maria gimenez almeida alburqueque da Silva')); # Maria G. A. A. da Silva

Note that I added an additional parameter called exceptions for names that should not be shortened, such as de, do and da, you can customize, for example added von the exception:

mb_shorten_name('Victor von Doom Junior', array( 'von' ))

Will return:

Victor von D. Junior

Also note that the third parameter is called $encode:

mb_shorten_name($name, [array $ignore, [$encode = null])

And you can adjust it for different encodings, or you can even try to detect the encoding with mb_detect_encoding, an example if you are sure of the type of encoding you see:

var_dump( mb_shorten_name($texto, null, 'UTF-8') ); # se a sua string for UTF-8

var_dump( mb_shorten_name($texto, null, 'ISO-8859-1') ); # se a sua string for ISO-8859-1

Example in Rep.it: https://repl.it/@inphinit/mbshortenname


If the names nay have accents or this is not a problem you can just try using:

<?php
/**
 * Encurta nomes sem acentos e com caracteres ASCII
 *
 * @param string $name    Define nome para ser encurtado
 * @param array  $ignore  Nomes/palavras que devem ser encurtados
 */
function shorten_name($name, array $ignore = array( 'de', 'da', 'do', 'dos' ))
{
    //Converte para case-title
    $name = ucwords(strtolower($name));

    //Divide a string
    $names = preg_split('#\s+#', $name);

    $j = count($names);

    // caso alguém tenha um só nome
    if ($j === 1) return trim($name);

    // Acaso só tenha 2 nomes
    if ($j < 3) return implode(' ', $names);

    $j--;

    $rebuild = array( $names[0] );

    for ($i = 1; $i < $j; $i++) {
        $ex = strtolower($names[$i]);

        if (in_array($ex, $ignore)) {
           $rebuild[] = strtolower($names[$i]);
        } else {
           $rebuild[] = substr($names[$i], 0, 1) . '.';
        }
    }

    $rebuild[] = $names[$j];

    return implode(' ', $rebuild);
}

var_dump(shorten_name('james bond de morais junior')); # James B. de M. Junior
var_dump(shorten_name('Kate Jennifer Bethan da Silva')); # Kate J. B. da Silva

Example in Rep.it: https://repl.it/@inphinit/shortenname

  • One thing, if the name has the words da, de, do, example "Miguel dos Santos Sobrinho" as it would be?

  • 1

    @Virgilionovic good idea for a new implementation, what you think best, omit or create an exception scheme?

  • So, I guess he didn’t have that prediction in the code, you have to take exception to be complete.

  • 1

    @Virgilionovic put as an optional array in the parameters

  • 1

    Chic ... !...

2

A function that takes the first and the last name, and abbreviates the middle names, if any. Removes words like "from", "do", "dos", "da", "das" and "and":

Examples:

  • Maria Pereira dos Santos -> Maria P. Santos

  • Virgulino Ferreira da Silva -> Virgulino F. Silva

  • Maria Santos -> Maria Santos

  • Antonio de Carvalho Souza Filho -> Antonio C. S. Filho

  • Maria das Dores Costa -> Maria D. Costa

Code:

function nomeAbrev($nometodo){

   $pattern = '/ de | do | dos | da | das | e /i';
   $nome = preg_replace($pattern,' ',$nometodo);
   $nome = explode(' ', $nome);

   $nomes_meio = ' ';

   if(count($nome) > 2){
      for($x=1;$x<count($nome)-1;$x++){
         $nomes_meio .= $nome[$x][0].'. ';
      }
   }

   $nomeabreviado = array_shift($nome).$nomes_meio.array_pop($nome);

   return $nomeabreviado;

}

echo nomeAbrev('nome');

Browser other questions tagged

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