Pick letters from the name string

5

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

$string = 'Renan Rodrigues';

Expected result: 'RR';

How to do this?

    
asked by anonymous 03.01.2017 / 16:49

3 answers

5

You can get the first character of the string by just indexing the variable to zero. To get the first letter after the space you can use str_pos() that will determine the position of the space, with it use substr() to copy the desired stretch (from the position of the space one characters, in this case the 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, the first call (with the third argument) will be returned to the left part of the delimiter, the second will return the part to the right.

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

Output:

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

Approach with regex

The regex \b\w captures every start of a word.

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

Output:

JSSJ

Related:

What is a boundary (b) in a regular expression?

    
03.01.2017 / 17:01
4

You can do it like this:

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

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

Example on IDEONE

But since the first letter can contain a punctuated character, it could give some coding error. So you could do:

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

Example on IDEONE

    
03.01.2017 / 16:58
3

Try this:

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