Log in

View Full Version : Regular expressions - matching two possible patterns using | (pipe)



chriswattsuk
12-14-2008, 10:02 PM
Hi guys,

Have been trawling the web for quite some time with no luck - hopefully somebody can help!

I have a regular expression that checks for a suitably formatted email address, and I have a seperate process for catching blanks. Therefore I need a regex that accepts either a valid email address or no data at all.

Here's my existing regex...


if(!ereg('^[0-9A-Za-z.-_]+@[0-9A-Za-z]+\.[A-Za-z.]+$',$value)) $badFormat = 1;

From web searching I gather that I can use the | (pipe) character to seperate two arguments in a regex, but I'm unclear on the syntax, this is what I tried...


if(!ereg('^[0-9A-Za-z.-_]+@[0-9A-Za-z]+\.[A-Za-z.]+$'|'^[A-Z]{4}$',$value)) $badFormat = 1;

... but it didn't work - as didn't countless other variations!

Can somebody help me? :confused:

Thanks in advance!

Chris.

james438
12-15-2008, 02:46 AM
<?php
$test='abc@domain.info';
if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$|^[Þ]{4}$/',
$test)) {echo "YES";}
else {echo "NO";}
?>

You could probably manipulate the above code to suit your needs. The Þ symbol is just that; a symbol. You said you wanted to match either email addresses or no data at all. I wasn't sure how to do no data at all, so I just added a random symbol to match if the data is not an email.

This example uses preg_match as opposed to ereg as I am more familiar with preg stuff and it is less processor heavy.

Lemme know if you have any other questions.

Master_script_maker
12-15-2008, 02:47 AM
try:

if(!ereg('^([0-9A-Za-z.-_]+@[0-9A-Za-z]+\.[A-Za-z.]+|)$',$value)) $badFormat = 1;
so it matches [0-9A-Za-z.-_]+@[0-9A-Za-z]+\.[A-Za-z.]+ or blank

Twey
12-15-2008, 07:02 AM
That's lovely, but disallows some perfectly valid email addresses (foo+bar@baz(quux)@my-site.co.uk, for example). The full specification of a valid email address is very complicated, and it's generally not worth your time to validate it beyond a very basic check:
if (!empty($value) && !preg_match('/^.+@.+\..+$/', $value))
$badFormat = true;Note: preg_match (http://www.php.net/preg-match)() is preferred to ereg (http://www.php.net/ereg)() in almost all cases. It's faster and more powerful.

chriswattsuk
01-11-2009, 07:10 PM
Thanks for your replies guys - have seen the light and decided to get my head into Perl regular expressions rather than POSIX so I can take advantage of the preg_match() functions!

Have read in quite a few places that the old ereg (POSIX) style functions are being removed in a future version (6?) the speed of Perl regex is far better.

Chris.