How can I abbreviate a name for 2 words, ignoring (of, of, das, das)?

2

I have a user table in the system where the user's full name is registered. However, at the time of displaying those names on the system, I must use only two words of that person's name to display. And when the words das , dos , da , do and de appear, I need those words to be ignored the next name is captured. But you should always display only 2 words of the person's name.

Examples:

 'Márcio da Silva da Costa' => 'Márcio Silva'
 'Lucas Oliveira Xavier'    => 'Lucas Oliveira'
 'Wallace de Souza'         => 'Wallace Souza'

How can I do this in PHP?

I currently have a code that does this, but I would like something simpler than that:

function nameSlice($name, $int = 2)
{
    $ignore = array('e', 'de', 'da', 'do', 'dos', 'das', 'a', 'le');

    $sliceName = explode(' ', $name);

    foreach ($sliceName as $key => $value) {
        if (in_array(strtolower($value), $ignore) && $int != $key) {
            $int++;
        }
    }

    $sliceName = array_slice(array_filter($sliceName), 0, $int);

    if (in_array(strtolower(end($sliceName)), $ignore, true)) {
        array_pop($sliceName);
    }

    return implode(' ', $sliceName);
}
    
asked by anonymous 01.10.2015 / 14:29

1 answer

2

A simple regular expression method will solve your problem:

function removeDaDeDiDoDu($name) {
           $name = preg_replace('/\s(d[A-z]{1,2}|a(.){1,2}?|e(.){1,2}?|le{1}|[A-z.]{1,2}\s)/i',' ',$name);
           return preg_replace('/\s+/i',' ', $name);
}

Here's an example working: link

Now if you want only two names, just get the first and last:

$nome = 'Wallace de Souza Vizerra';
$allNames = explode(' ', $nome);
$nome = $allNames[0].' '.$allNames[count($allNames)-1];
echo $nome;

Here's the example: link

    
01.10.2015 / 15:20