Jump to content

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

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));

?>

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.

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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