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);
}