Character manipulation in PHP

Asked

Viewed 52 times

3

Example, we receive a login this way

joao.silvestre

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

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

jsilvest

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

3 answers

5


You can do it like this, assuming there’s always gonna be a point 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

  • Perfect. It worked right :) Thank you very much.

  • You’re welcome @Rafaelbrito

  • . . time: 6.9μs

2

This is a variation of @Miguel’s response:

You can use this:

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

It works in PHP 5.5 and above, unless mistakenly.

1

Option with REGEX

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

Time: 0.00000905990600585938 (9μs)

Browser other questions tagged

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