1

I have a function that will find an email string that is in a specific format. I need to find this specific email string within the larger string. The specific email string I need to find has to be in this format:

"email":"[email protected]"

I need to find any occurrence of this type of string. Here is my function to find that:

 function find_email_schema($str){

      preg_match_all('/["email":"]+[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i', $str, $matches);

      return $matches;

  } 

However, this function isn't working as expected, it finds other emails in the larger string that aren't in this format:

"email":"[email protected]"

I only want emails that start with "email":

I know that the pattern I'm passing to preg_match_all isn't correct, but I'm not sure what I need to change to only obtain emails that comply with the above format. What do I need to alter in my regex pattern to get this working?

This is the pattern I'm using:

 /["email":"]+[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i
2
  • 2
    ["email":"]+ should be replaced with "email":" Commented May 10, 2023 at 14:51
  • 1
    [\._a-zA-Z0-9-] can also be shortened to [-.\w]. Commented May 10, 2023 at 15:44

1 Answer 1

3

Because the "email": part is literal, you don't need to enclose it between [ ], so try this one (I also add the email address enclosing " optional with the ?):

 /"email":"?[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+"?/i

[ ] are used to declare character ranges like a-z indicating from a to z, like you did for the next part.

Let's try it on regex101.com:

enter image description here

Sign up to request clarification or add additional context in comments.

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.