Regex / PHP Question...

nvanprooyen

Fortes Fortuna Adiuvat
Dec 8, 2008
3,189
82
0
Orlando, FL
I'm trying to figure out what I'm doing wrong here:

$regex = '/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/';
preg_match($regex,$data,$match);
var_dump($match);
echo $match[1];

I have a bunch of text inside of $data and I'm trying to get an email address out of it using preg_match. Right now, the array is empty, but there are definitely email addresses inside of $data. Any idea what I'm doing wrong?
 


Try
/[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})/

One of the problems is the way you're doing it is not case insensitive, either you have to account for that in the expression, or use i after the final /

The way you got it now, only emails in all CAPS will be found.
 
  • Like
Reactions: nvanprooyen
You could also use A-z, or after the last / ad i (as Karl said) to indicate a case insensitive search. You might want the plus sign in the name part of your email address as that is a valid character, although uncommon. You might not want to restrict your TLD to 4 characters as there are TLDs like .museum so {2,} might be better.

So you could change KBs string to /[A-z0-9._-+]+@[A-z0-9._-]+\.([A-z]{2,})/

I've used this one before /^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i