<?php
function extract_emails($str) {
// 符合 RFC 5322 簡化版的 Email 正則
$regexp = '/([a-z0-9_.-])+@(([a-z0-9-])+.)+([a-z0-9]{2,4})+/i';
preg_match_all($regexp, $str, $matches);
return isset($matches[0]) ? $matches[0] : [];
}
?>
<?php
$test_string = 'This is a test string...
test1@example.org
Test different formats:
test2@example.org;
<a href="test3@example.org">foobar</a>
<test4@example.org>
strange formats:
test5@example.org
test6[at]example.org
test7@example.net.org.com
test8@ example.org
test9@!foo!.org
foobar';
print_r(extract_emails($test_string));
/*
輸出結果:
Array
(
[0] => test1@example.org
[1] => test2@example.org
[2] => test3@example.org
[3] => test4@example.org
[4] => test5@example.org
[5] => test7@example.net.org.com
)
*/
?>
([a-z0-9_.-])+:本地部分允許字母、數字、底線、點、連字號。@:必須包含單一 @ 符號。(([a-z0-9-])+.)+:域名部分由一或多個標籤組成,每標籤以點結尾。([a-z0-9]{2,4}):頂級域名 2-4 字元(如 com, org, net, info)。i 模式:不區分大小寫。此正則為簡化版,無法涵蓋所有 RFC 5322 合法格式(如帶引號的本地部分、IP 域名等)。生產環境建議使用 filter_var($email, FILTER_VALIDATE_EMAIL) 或成熟函式庫(如 egulias/email-validator)。