PHP preg_match help

Discussion in 'PHP' started by norfstar, Jun 29, 2011.

  1. #1
    I have been using the following function to test whether email addresses are a valid format for years:

    if (preg_match("/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.([a-z][a-z]+)|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i", $var)) {
    	// Email is valid
    }
    Code (markup):
    It turns out however, the apostrophe character can legimately occur in the mailbox name (not the domain name). Can anyone modify the above so if an email address is like john.o'smith@example.com it will return valid?

    Many thanks,
     
    norfstar, Jun 29, 2011 IP
  2. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #2
    The pattern already works. Test it yourself.
     
    Alex Roxon, Jun 30, 2011 IP
  3. norfstar

    norfstar Peon

    Messages:
    1,154
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for your reply Alex. However that code was considering apostrophes in email addresses as invalid.

    I have resolved the issue by using the filter_var() function that was introduced in PHP 5.2.0.
     
    norfstar, Jul 1, 2011 IP
  4. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #4
    <?php
    
    if (preg_match("/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.([a-z][a-z]+)|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i", "a'lex.roxon@domain.com")) {
    	echo 'Email is valid.';
    }
    
    ?>
    Code (markup):
    Output: Email is valid.

    Didn't change your pattern at all. Tested in PHP 5.3.1.
     
    Alex Roxon, Jul 1, 2011 IP
  5. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #5
    Emm aren't you basically letting everything through up to @domain . . . ?

    Why not just use (.+)@

    
    <?php
    
    if (preg_match("/^(.+)@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.([a-z][a-z]+)|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i", "a'lex.roxon@sub.Domain.com.uk")) {
    	echo 'Email is valid.';
    }
    
    ?>
    
    PHP:
    I'm just curious myself as to why you need to match: garbage@ ?
     
    MyVodaFone, Jul 1, 2011 IP