2
I have a user table on the system where the full user name is registered.
But, when displaying these names in the system, I should only use 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 it 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);
}
What have you done? : D Are you sure you’re going to ignore the last name? It’s usually the most important one. But not always. So automating this can produce useless results.
– Maniero
Demands of my boss, @bigown!
– Wallace Maxters
@bigown, I could tell there’s a scam in my code, right. This was the time I was creating a class called
Util
and created some static method in it.– Wallace Maxters
Gambiarra is normal, if time allows, I take a look.
– Maniero
Should you only get the first and last names? Or the last?
– Marcelo de Andrade
@Marcelodeandrade, as in the example shown in the question. First and second. If the second word is
de|das?|dos?
, then we ignore that word and skip to the next.– Wallace Maxters
@bigown, I got this http://ideone.com/NdLDPX
– Wallace Maxters
I think this question was good for me. It forced me to refactor systems resources (which I did myself) that are outdated. The first step towards healing is admitting the problem. In this case, I admit my gambit.
– Wallace Maxters