Jump to content

Archived

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

jaymc

[SOLVED] Extract email address from string

Recommended Posts

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

 

$string = "email@site.com"

$string = "hello my email email@site.com"

$string = "hello my email email@site.com add it please"

 

In all 3 cases it must return email@site.com with no trailing spaces or any other of the surrounding text

Share this post


Link to post
Share on other sites

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@address.com blah blah blah email2@address.com";

$emails = extract_emails_from($text);

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

?>

Share this post


Link to post
Share on other sites

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@site.com";

$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.

Share this post


Link to post
Share on other sites

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

 

Share this post


Link to post
Share on other sites

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...

Share this post


Link to post
Share on other sites

×
×
  • 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.