Regex to Extract an Email Address

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • miraan
    New Member
    • Apr 2008
    • 24

    Regex to Extract an Email Address

    Hi all,

    Please can someone help me! I have experimented on this for hours but I am new to regex! Here is my problem:

    I want to get the email address admin@example.n et out of this string and store it in $email.

    The string is:
    <a href='mailto:ad min@example.net '>admin@example .net</a>

    Please can someone give me code to get the email address out of this string and place it in $email.

    All help will be greatly appreciated!
  • Gulzor
    New Member
    • Jul 2008
    • 27

    #2
    Hi,

    I use the following regular expression to extract emails from files :

    ^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$

    source : http://www.developer.com/lang/php/article.php/3290141

    Comment

    • miraan
      New Member
      • Apr 2008
      • 24

      #3
      hmmm,
      can you give me the function for that. I am new to regex and i cant seem to use that expression with ereg_replace. Here is what i have tried to do:

      Code:
      <?php
      $string="<a href='mailto:admin@example.net'>admin@example.net</a>";
      $string=ereg_replace("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",$1,$string);
      echo $string;
      ?>
      I am not even sure if in ereg_replace you are allowed to use regex as a string pattern or if you can use $1 to use the first match to replace $string with (i.e. the email address found in the string.

      Comment

      • miraan
        New Member
        • Apr 2008
        • 24

        #4
        Sorry, heres some improved code:

        Code:
        <?php
        $string="<a href='mailto:admin@example.net'>admin@example.net</a>";
        if(ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $string, $regs)) {
          	$string=$regs[1];
        } else {
        echo "No matches!<br>";
        echo $string;
        }
        ?>

        Comment

        • Gulzor
          New Member
          • Jul 2008
          • 27

          #5
          I wrote that script to extract all email addresses contained into a file : (don't forget to replace page.html with your file)

          [php]
          <?php

          $buffer=file_ge t_contents('pag e.html');

          /* pas de ^ et $ car plusieurs emails par lignes !*/
          $regex='`([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})`';


          $matches=array( );
          preg_match_all( $regex, $buffer, $matches);

          $emails=array_u nique($matches[0]);

          sort($emails, SORT_STRING);


          foreach($emails as $email){
          echo "$email\r\n ";
          }


          //print_r($emails );

          ?>
          [/php]

          Comment

          Working...