Take letters from name string

Asked

Viewed 3,460 times

6

I need to take the first letter of the name and the first letter after the space, in case it would be like this:

$string = 'Renan Rodrigues';

Expected result: 'RR';

How to do this ?

  • String can have a third or fourth name?

  • 1

    @rray may have yes

  • 2

    would choose to use regex, to be more performative and to ensure a greater security qto to accents and other situations that you do not expect.

4 answers

6


You can take the first character of the string, just index the variable to zero. To take the first letter after the space you can use str_pos() that will determine the position of space, with it use substr() to copy the desired chunk (from the position of the one-character space, in the case of R)

echo $string[0] . substr($string, strpos(' ', $string), 1);

Another alternative is to call the function strstr() it will 'cut' the string into two pieces, in the first call (with the third argument) the left part of the delimiter will be returned, while the second returns the right part.

$string = 'Renan Rodrigues';
$iniciais = strstr($string, ' ', true)[0] . trim(strstr($string, ' ')[1]);

If your string has more than two items to pick up the first letter or if by chance the string has two or more spaces followed recommend using a more elaborate function like:

function iniciais($str){
    $pos = 0;
    $saida = '';
    while(($pos = strpos($str, ' ', $pos)) !== false ){
        if(isset($str[$pos +1]) && $str[$pos +1] != ' '){
            $saida .= substr($str, $pos +1, 1);
        }   
        $pos++;
    }
    return $str[0]. $saida;
}


$arr = ['Abc Jr Silva', 'AB      ', 'TEste     123, Zxw', 'A1 B2 C3 D4', 'Nome'];
foreach($arr as $item){
    var_dump(iniciais($item));
}

Exit:

string 'AJS' (length=3)
string 'A' (length=1)
string 'T1Z' (length=3)
string 'ABCD' (length=4)
string 'N' (length=1)

Approach with regex

A regex \b\w captures each word start.

$string = 'João Silva Sauro Jr';
preg_match_all('/\b\w/u', $string, $m);
echo implode('',$m[0]);

Exit:

JSSJ

Related:

What’s the use of a Boundary ( b) in a regular expression?

5

You can do it like this:

$partes = explode(' ', $nome);

echo $partes[0][0]
echo $partes[1][0]

Example in IDEONE

But as the first letter may contain an accented character, it could give some encoding error. So, you could do:

 echo mb_substr($partes[0], 0, 1, 'UTF-8');
 echo mb_substr($partes[1], 0, 1, 'UTF-8');

Example in IDEONE

4

Try it like this:

$string = 'Renan Rodrigues';
$nomeSeparado=explode(" ",$string);
$iniciais= substr($nomeSeparado[0],0,1).substr($nomeSeparado[1],0,1);
echo $iniciais;

1

 public function index(){          

     // Array ( [0] => Raylan [1] => Soares [2] => Campos )     
     $names = explode(' ', Auth::user()->name);

     // Variavel recebe a verificação se tem mais de dois nomes,
     // caso tenha irá armazenar primeiro e ultimo nome.       
     $twoNames = (isset($names)) ? $names[0] . ' ' . end($names) : $names[0];

     // Variavel recebe a primeira letra do primeiro nome e a 
     //primeira letra do último nome função end() pega a ultimo valor do array.     
     $iniciais = strstr($twoNames, ' ', true)[0] . trim(strstr($twoNames, ' ')[1]);

     // retorna para a view o nome e ultimo nome na variavel $twoNames, e as 
     //Iniciais desse nome na variavel $iniciais.
     return view('index',compact('twoNames','iniciais'));
}
  • Why the name index()? Would not be more descriptive iniciais() or monograma()?

Browser other questions tagged

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