1

I've been trying this for quite some time now but to no avail

I need to read a string and return the substring word that contains '@' for instance, there is a string like "andrew garfield invited as andrew@gomail.com" want the function to return substring "andrew@gomail.com"

tried explode, strpos, and substr so as to find the position of @ and then find spaces and then explode cant really get it to work your kind help is appreciated

Yashesh
  • 47
  • 1
  • 8
  • first, explode by a space so you have the single words in an array. then, loop over the array and look if your word contains an at. if it does: return it. there's not more to it. – Franz Gleichmann Oct 19 '16 at 07:15

4 Answers4

2

A straight-forward approach to get all such substrings:

$s = "andrew garfield invited as andrew@gomail.com or man@ohman.com";
$ss = explode(" ", $s);
$res = array();
foreach($ss as $x) {
    if (strpos($x, "@") > -1) {
        array_push($res, $x);
    }
}
print_r($res);

See an online PHP demo.

If you prefer a regex, you may match one or more non-whitespace symbols with \S+, and use \S+@\S+ regex to extract chunks of non-whitespaces + @ + non-whitespaces (with the min length of 3):

$s = "andrew garfield invited as andrew@gomail.com or man@ohman.com";
$res = array();
preg_match_all('~\S+@\S+~', $s, $res);
print_r($res);

to get rid of any non-word char at the end, add \b at the end of the regex. See this PHP demo.

NOTE: To grab emails from a longer string, you may use an approach described by Rob Locke in How to get email address from a long string SO thread.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

I think the best solution for you is regex. This is PHP code for you:

$re = '/(?<=\b)\w([\w\.\-_0-9])*(@| at )[\w0-9][\w\-_0-9]*((\.| DOT )[\w\-_0-9]+)+(?=\b)/mi';
$str = 'andrew garfield invited as andrew@gomail.com';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);
Kacper Polak
  • 1,411
  • 15
  • 24
0
$result = array();
$text_array = explode(' ', 'andrew garfield invited as andrew@gomail.com');

for($i=0; $i<sizeof($text_array); $i++)
{
    if(strpos($text_array[$i], '@'))
    {
        array_push($result, $text_array[$i]);
    }
}

echo "<pre>";
print_r($result);
echo "</pre>";
Aakash Martand
  • 926
  • 1
  • 8
  • 21
0

Keep things simple :)

$str = "andrew garfield invited as andrew@gomail.com";
$strArr = explode('@',$str);
$pieces = explode(' ', $strArr[0]);
$last_word = array_pop($pieces);
$email =  $last_word.'@'.$strArr[1];
echo $email;
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130