Pick first name with Regular Expression

Asked

Viewed 1,021 times

6

I need to get the first name with regular expression, only I’m not getting it right. Today I use the code like this:

<?php
preg_match('/[[:alnum:]]+/i', 'Alisson Acioli', $matches);

return $matches[0];
?>

Output: Alisson

When the name is composed:

<?php
preg_match('/[[:alnum:]]+/i', 'João', $matches);

return $matches[0];
?>

Output: Jo

  • Use the modifier u to capture multibyte characters. strstr() already fix it => Printing a String until a space is found

  • And why you need to pick with regular expression?

  • really want to do this with ER?

  • 1

    Coincidence, I just saw a similar question: http://answall.com/questions/105977/com-esta-regra-abaixo-como-fa%C3%A7o-para-mostrar-o-primeiro-e-o-%C3%Baltimo-nome-do-Usu%C3%A1

5 answers

5

You asked with regular expression, but I’ll leave some alternatives with operation string, if someone prefers without Regex (in fact, Regex is not for these simple things).

Explodes

$tokens = explode( 'Alisson Acioli', $nome );
return $tokens[0];

with verification if found:

$nome = 'Alisson Acioli';
$tokens = explode( ' ', $nome );
return count( $tokens ) > 0 ? $tokens[0] : '';


Substr + strpos

$nome = 'Alisson Acioli';
return mb_substr( $nome, 0, mb_strpos( $nome, ' ' ) );

with verification if found:

$pos = mb_strpos( $nome, ' ' );
return $pos !== false ? mb_substr( $nome, 0, $pos ) : '';


strstr

$nome = 'Alisson Acioli';
return mb_strstr( $nome, ' ', true );


In all cases, the prefix mb_ is for strings multibyte. If used encodings 1 byte only, can remove prefixes.

2

Another way to solve with regex is:

$str = 'joão da silva';

preg_match('/\[a-z]+/ui', $str, $m);

The PCRE modifier u is important in this case to make the catch of accented characters otherwise will capture only singlebyte characters as in the question example. Already the modifier i make the capture caseinsensitive or be both do if the letters are uppercase or minusculas.

Other option to solve this problem see in: Printing a String until a space is found

2

2

This occurs due to accentuation of the word john, for the [[:alnum:]] does not consider accentuation. Consider using:

preg_match('/[\p{Latin}\d]+/i', 'Joaõ da Silva', $matches);
echo $matches[0];

0


Try to use this code:

<?php
    preg_match('/[^\s]*/', 'Qualquer Nome', $matches);
    return $matches[0];
?>
  • 1

    This regex will take names like that too: 34566...

Browser other questions tagged

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