extracting an email address from a text field

11 posts by 2 authors in: Forums > CMS Builder
Last Post: November 27, 2013   (RSS)

Hi All,

I’ve got a text field ( internal_notes ) in my user accounts table which contains an email address (always surrounded by spaces), and I want to capture that email address and ultimately insert it into the email address field in the same record.

I found the following function at: http://stackoverflow.com/questions/1028553/how-to-get-email-address-from-a-long-string

I’m sure it’s something really silly, but don’t seem to be able to get it working.

Any ideas?

Thanks,

Jerry Kornbluth
 

<?php
function extract_email_address ($string) {
   $emails = array();
   $string = str_replace("\r\n",' ',$string);
   $string = str_replace("\n",' ',$string);

   foreach(preg_split('/ /', $string) as $token) {
        $email = filter_var($token, FILTER_VALIDATE_EMAIL);
        if ($email !== false) {
            $emails[] = $email;
        }
    }
    return $emails;
}
?>

<?php foreach ($accountsRecords as $record): ?>

<?php echo extract_email_address ($record['internal_notes']) ?>

 <?php endforeach ?>

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By Dave - November 18, 2013

Hi Jerry,

Can you provide some example content that it's not working for? 

Here's a working example:

function extract_email_address ($string) {
   $emails = array();
   $string = str_replace("\r\n",' ',$string);
   $string = str_replace("\n",' ',$string);

   foreach(preg_split('/ /', $string) as $token) {
        $email = filter_var($token, FILTER_VALIDATE_EMAIL);
        if ($email !== false) { 
            $emails[] = $email;
        }
    }
    return $emails;
}

$string = "Hello there this
is a user@example.com test of emails
in a string@example.com";

$emails = extract_email_address($string);
print "Emails found: ";
print_r($emails);
exit;
  

Outputs: Emails found: Array ( [0] => user@example.com [1] => string@example.com )

Let me know, thanks!

Dave Edis - Senior Developer
interactivetools.com

Thanks again,

I'll try it out

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

Hi Dave,

I’ve managed to isolate all the email addresses from the internal_notes text field in each user's record using this function:

<?php
function extract_emails_from($string){
    preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
    return $matches[0];
}
    ?>

<?php foreach ($accountsRecords as $record): ?>

<?php $text =  htmlencode($record['internal_notes']) ?>
<?php $emails = extract_emails_from($text);?>
The Email Alone: <?php foreach($emails as $email) {
    echo $email ;
}
?>
 <?php endforeach ?>

My next challenge is to insert the email addresses into the currently blank email field in that user’s record. (without breaking anything...)

Any suggestions?

Thanks,

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

Thanks for this Dave,

Looks pretty scary, so I think I'll try it on a test install first.

I'll let you know how it goes

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By Dave - November 21, 2013

Hi Jerry, 

Sure thing.  Here's some more self-documenting code so you can see how it works:

// uncomment this line once you've confirmed emails look as desired
$tableName    = 'accounts';
$recordNum    = $record['num']
$where        = '';
$colsToValues = array();
$colsToValues['your-email-field'] = $emailsAsCSV;
mysql_update($tableName, $recordNum, $where, $colsToValues);

So basically what it does is update records in 'accounts' that match the recordNumber and/or where statements, updating ONLY the fieldnames/columns listed in $colsToValues.  If you wanted to do a test run you could create a field called 'test' and update that with $colsToValues['test'] instead of the other fieldname (whatever that other fieldname may be that you want to update).

Hope that helps!

Dave Edis - Senior Developer
interactivetools.com

Hi Dave,

I added the if statement below to leave any existing emails alone, but came up with one interesting issue.

Some of the records have more than one email address in the internal_notes field.

How can I limit the capture to only the first one?

Thanks as always,

Jerry Kornbluth

    <?php
  foreach ($accountsRecords as $record) {
    $text   = htmlencode($record['internal_notes']);
    $emails = extract_emails_from($text);
   if ($record['email']) { $emails[] = $record['email']; } // add any pre-existing email content
    $emailsAsCSV = implode(',', $emails);
    print "User {$record['fullname']} has these emails: $emailsAsCSV<br/>\n";
   // uncomment this line once you've confirmed emails look as desired
 if (!$record['email']) { mysql_update('accounts', $record['num'], null, array('email' => $emailsAsCSV));}
    
  }
?>

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By Dave - November 22, 2013

Hi Jerry, 

If you only want the first captured emails, and don't need to worry about what was already in the field you are updating, then you could use this (untested) code:

<?php 
  foreach ($accountsRecords as $record) {
    if ($record['email']) { continue; } // skip records that already have an email set
    $allEmails  = extract_emails_from( $record['internal_notes'] ); 
    $firstEmail = @$allEmails[0];
    print "User {$record['fullname']} will get this email: $firstEmail<br/>\n"; 
    mysql_update('accounts', $record['num'], null, array('email' => $firstEmail ));}
  }
?>

I removed htmlencode(), if you need that for some reason just add it back in.

Let me know how it goes!

Dave Edis - Senior Developer
interactivetools.com

By gkornbluth - November 22, 2013 - edited: November 22, 2013

WOW! It's  good... And Elegant!

Worked just as you expected (although I had my arms, fingers, legs and toes crossed when I fired it up)

This is definitely one for the Cookbook!

Thanks,

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php