-1

I have to create a nickname from the email address of the user. For example: mario-rossi79@gmail.com

in this case the nickname that I have to create should contain only alphanumeric characters: mariorossi79

How can I do that?

Istvan Szasz
  • 1,307
  • 17
  • 31
Carol Casta
  • 75
  • 1
  • 9
  • 1
    Have you tried anything yet? – Aleks G Aug 06 '13 at 08:35
  • 2
    Please note that `mario-rossi79@gmail.com` and `mario-rossi79@yahoo.com` can be two different persons that would like to use your service. – Martin Thoma Aug 06 '13 at 08:37
  • 1
    @moose, What about mariorossi79@yahoo.com and mario-rossi79@yahoo.com? – 7stud Aug 06 '13 at 08:41
  • Using regexs to validate email addresses or even combining the two in any way is really not the best thing to do. See http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – Alex Aug 06 '13 at 09:35

2 Answers2

2

Try this:

$email =  'mario-rossi79@gmail.com';
$arr = explode("@", $email);
$result = preg_replace("/[^a-zA-Z0-9]+/", "", $arr[0]);
echo $result;
Ranjan
  • 263
  • 2
  • 11
0

you can do it in 2 passes. first remove the @domain second remove the none alpha numeric.

$email = "mario-rossi79@gmail.com";
$user = preg_replace("/@.*$/", "", $email);
$nickname = preg_replace("/[^A-Za-z0-9]/", "", $user);
DevZer0
  • 13,433
  • 7
  • 27
  • 51