0

I want to get a the part of string of an email after @ using regular expression. For example, I have the string '[email protected]' and i want to get 'gmail.com'. I wrote /^@./ but doesn't work- I wrote

preg_match('/^@./', $string, $output);
print($output);

How can i fix it?

1
  • What is the reason behind down-vote? Commented Sep 16, 2017 at 4:30

2 Answers 2

2

You have several mistakes. First, with the caret you're telling you want the @ symbol to be first in the string. So for an email that will never match. Then, you need to set a capturing group to actually get the part after the @. So it'd look like this:

<?php
$mail = "[email protected]";
preg_match('/@(.+)/', $mail, $output);
print_r($output[1]); // gmail.com

However, this is such a simple task that you should not use a regular expresion. explode() will do:

<?php
$mail = "[email protected]";
$mailArray = explode("@", $mail);
print_r($mailArray[1]); // gmail.com
Sign up to request clarification or add additional context in comments.

3 Comments

Can you tell me the reason behind down-voting my post?
I didn't? Might have been a mistake. Did you delete it?
@SahilGulati undelete your answer, I will of course remove downvote if it was mine.
1

Why regex for this kind of simple task? use strpos with the combination of substr or just used explode() with @ as first parameter as directed by other answers.

$email_string = "[email protected]";    
$result = substr($email_string, strpos($email_string, "@") + 1);    
echo $result ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.