Capturing email addresses with Regular Expressions
We all know that capturing email addresses with regular expressions can be tricky but I think, in this case at least, the following might be useful. If not, you can at least use it as a building block to tweak and make suitable for your particular needs.
Description
array capture_email( string $sSubject)
Searches sSubject for email addresses present within it.
Function Definition
PHP Code:
function capture_email($sSubject)
{
static $sRegexFu = '
/
(?# --
# This pattern captures
# only real and proper
# email address!
# -- )
\b(?:[\!"#\$%\'\(\)\*\+,\-\&
\:;@ \?\^
_` \{ \| \}
\] \* \? \[
\! \# $% ])
*\K (?: [a-z0-9]+ @[ {}
&\' *+ \/ =?
^`a-z~-]+(?:\.[a-z0-9]+)?)\b
(?# -- End of Email Capture --)
/x';
// Return the array of emails (which may be empty!)
if (preg_match_all($sRegexFu, $sSubject, $aEmails) !== FALSE)
return array_shift($aEmails);
return FALSE;
}
Returns
An array of email addresses present within the sSubject string (an empty array if none) or FALSE on error.
Example
PHP Code:
print_r(
capture_email('
Get in touch at email@domain.com
but make sure not to be a silly
person by spamming nospam@domain.com!
')
);
The above example will output:
Code:
Array
(
[0] => email@domain.com
[1] => nospam@domain.com
)
Off Topic:
*giggle*
Bookmarks