views:

8744

answers:

6

Please tell me how to use the various symbols used for expression matching in preg_match function of PHP.

Besides basic information, please give example for checking a valid e-mail address and a string that should not contain / : ; { } * &

+4  A: 

this is the best set of introductory regex information I've seen recently.

Lance Kidwell
Thanks!Very comprehensive article
OrangeRind
+1  A: 

Jeff Atwood recently had an article on his coding horror blog about regular expressions. Check out "Regular Expressions for Regular Programmers".

Copas
nice articlepretty hilarious i must say
OrangeRind
A: 

To check for a valid mail you can either use build in functionality (filter_var()/FILTER_VALIDATE_EMAIL) or use nice ready to use libraries which are compliant to the current RFC. PHP : Parsing Email Adresses in PHP. For examples on preg_match() you can go to the php website and a full list regular expression options is available on Wikipedia. To learn about Regex I recommend "The Regex Coach".

merkuro
+2  A: 

Simple example.. Verifying $var which is a string verifying and checking for (a to z AND A to Z) characters.

<?php
$var = 'hello';
if (ereg("[a-zA-Z]", $var)) {
  echo 'it was typed correctly';
} else {
  echo 'it was not typed correctly';
}
?>

more regular expressions syntax exemples: http://www.regexlib.com/

EDIT:

if (ereg("^([0-9,a-z,A-Z]+)([.,_]([0-9,a-z,A-Z]+))*[@]([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])?$", $email)) {

  echo 'email ok';

} else {

  echo 'email not ok';

}

Regards.

Fábio Antunes
thanks for the link!
OrangeRind
I recommend using regular expressions(regex) for string/email validation..(ereg in Php)The example just up i use it for 2 years.. Never let me down.Sure there yes a smaller regex expression.. But i like to keep the ones i know it works well.
Fábio Antunes
Anyone just starting out with regexes in PHP should use the preg suite, not ereg. preg is based on the PCRE library, and it's one of the most powerful, feature-rich flavors in existence. ereg, based on the POSIX standard, uses a different syntax and is much less powerful; it's really only supported for historical reasons.
Alan Moore
From the PHP manual page on ereg. ( http://php.net/manual/en/function.ereg.php )"WarningThis function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged."
Keith
A: 

I know the question is about PHP, but my purpose is to illustrate the intricacies of email address validation: To check if an email address conforms to RFC 2822, you can use the Perl module Email::Address. Do take a look at the source of that module as well as the RFC.

Sinan Ünür
A: 

If I give $var = 'hello87%^$' also returning "it was typed correctly";