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
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: