首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 正則表達式提取字串中的 Email 地址

     編輯:PHP 相關知識

提取函數

<?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)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved