Regexp for extracting a mailto: address

半腔热情 提交于 2019-11-28 14:29:37

If you want to match the whole thing from :

$r = '`\<a([^>]+)href\=\"mailto\:([^">]+)\"([^>]*)\>(.*?)\<\/a\>`ism';
preg_match_all($r,$html, $matches, PREG_SET_ORDER);

To fastern and shortern it:

$r = '`\<a([^>]+)href\=\"mailto\:([^">]+)\"([^>]*)\>`ism';
preg_match_all($r,$html, $matches, PREG_SET_ORDER);

The 2nd matching group will be whatever email it is.

Example:

$html ='<div><a href="mailto:test@live.com">test</a></div>';

$r = '`\<a([^>]+)href\=\"mailto\:([^">]+)\"([^>]*)\>(.*?)\<\/a\>`ism';
preg_match_all($r,$html, $matches, PREG_SET_ORDER);
var_dump($matches);

Output:

array(1) {
  [0]=>
  array(5) {
    [0]=>
    string(39) "test"
    [1]=>
    string(1) " "
    [2]=>
    string(13) "test@live.com"
    [3]=>
    string(0) ""
    [4]=>
    string(4) "test"
  }
}

There are plenty of different options on regexp.info

One example would be:

\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b

The "mailto:" is trivial to prepend to that.

/(mailto:)(.+)(\")/

The second matching group will be the email address.

You can work with the internal PHP filter http://us3.php.net/manual/en/book.filter.php

(they have one which is specially there for validating or sanitizing email -> FILTER_VALIDATE_EMAIL)

Greets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!