Jump to content

[SOLVED] Extract email address from string


jaymc

Recommended Posts

Im looking for some code to extract an email address from a string, It needs to work for the following

 

$string = "[email protected]"

$string = "hello my email [email protected]"

$string = "hello my email [email protected] add it please"

 

In all 3 cases it must return [email protected] with no trailing spaces or any other of the surrounding text

I got this straight of a tutorials website as it's a lot faster than writting it...

 

<?php

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

$text = "blah blah blah [email protected] blah blah blah [email protected]";

$emails = extract_emails_from($text);

print(implode("\n", $emails));

?>

Beatin to it, but hey I did alot of hard work...actually I just pulled this from preg_match and modified a bit :)

<?php
$string = "hello my email [email protected]";

$pattern = '/([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])' .
'(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)/i';

preg_match ($pattern, $string, $matches);
echo "We extracted " . $matches[0] . " from $string";
?>

 

Should do it.

Ok.. How about this scenario, slightly trickier

 

 

$string = "hello go here www.website.com/jaymc please"

$string = "hello go here http://www.website.com/jaymc please"

$string = "hello go here website.com/jaymc please"

$string = "hello go here http://website.com/jaymc please"

 

In all 3 cases it must return the URL in any of its forms (www.website.com/jaymc, http://www.website.com/jaymc, website.com/jaymc, http://website.com/jaymc)  with no trailing spaces or any other of the surrounding text

 

Are you testing us, or are you just not trying to find a solution on your own?

 

EDIT....

 

I need to be a little more constructive...

 

Check out Nick's Regular Expressions Tutorial

 

I just did and it's a great read, will give you an insight into what you're trying to do and more...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.