split email from string with PHP
I need to be able to split a string that contains email's From
information. From the string I need to extract $NAME
and $EMAIL
or whatever is available.
The string can be in the following formats开发者_StackOverflow社区:
"Santa Clause" <santa@example.com>
Santa Clause <santa@example.com>
<santa@example.com>
preg_match('#(?:"(?<name>[^"]+)"|(?<name>.+))?<(?<email>.+)>#U', $string, $matches);
echo var_dump($matches);
preg_match('#(?:"(?<name>[^"]+)"|(?<name>.+))?<(?<email>[^>]+)>#U', $string, $matches);
echo var_dump($matches);
Try one of the above. The former will allow more valid emails, whereas the latter is faster.
$string_to_check = '"Santa Clause" <santa@npole.com>'
$matches = array();
preg_match('/?([^<"]*)"?\s*<(\S*)>/',$string_to_check,$matches);
$matches[1] //=> Santa Claus
$matches[2] //=> santa@npole.com
If the separator is always the same character (e.g. the semicolon):
$items = explode($separator, $from);
Otherwise, browse around in the preg_XXX
functions for regex-based string splitting.
For the mail adress, have a look at http://php.net/manual/en/function.preg-match.php. This is a function that matches a string against a regular expression. Here's a short intro into how to use regular expressions with PHP.
If you want to match the name also, it will be some effort, so I suggest you first develop a regular expression that can extract an email address out of your string and then augment it to find the name also.
Found this and it works great!
$parts = preg_split('/[\'"<>]( *[\'"<>])*/', $text, -1, PREG_SPLIT_NO_EMPTY);
精彩评论