Character manipulation in PHP

3

Example, we received a login this way

joao.silvestre

And I want to get the string with the following rule:

The first letter of the name + the 7 letters that comes after the point that separates the name of the last name, for example:

jsilvest

How do I capture this string by following the above rules in PHP?

    
asked by anonymous 05.01.2017 / 12:41

3 answers

5

You can do this, assuming that there will always be a dot between the names:

$username = 'joao.silvestre';
$names = explode('.', $username);
$final = $names[0][0].substr($names[1], 0, 7); // no segundo nome vamos extrair os caracteres a começar no indice 0 até termos 7 caracteres
echo $final; // jsilvest

DEMONSTRATION

    
05.01.2017 / 12:46
2
  

This is a variation of the @Miguel response:

You can use this:

$nome  = 'joao.silvestre';
$final = $nome[0].substr(explode('.', $nome)[1], 0, 7);

This works in PHP 5.5 and above, unless misled.

    
05.01.2017 / 12:52
1

Option with REGEX

$str = 'joao.silvestre';
preg_match('/[^.][\w]{6}/', $str, $rs);
echo $str[0].$rs[0];

Time: 0.00000905990600585938 (9μs)

    
05.01.2017 / 14:39