PHP 從字串提取所有英文單詞:正則 + 去重 + 排序一體化函式
核心函式實作
<?php
/**
* 從字串提取所有英文單詞
*
* @param string $str 輸入字串
* @param bool $distinct true=去重(預設),false=保留重複
* @return array 單詞陣列(已按字母序排序)
*/
function split_en_str(string $str, bool $distinct = true): array {
// 匹配連續英文字母(A-Z, a-z)
preg_match_all('/([a-zA-Z]+)/', $str, $matches);
$words = $matches[1] ?? [];
if ($distinct) {
$words = array_unique($words);
}
sort($words, SORT_STRING | SORT_FLAG_CASE); // 不分大小寫排序
return array_values($words); // 重置索引
}
?>
使用範例
<?php
$text = "Hello World! This is a test. Hello again, world-of-PHP.";
// 預設:去重 + 排序
print_r(split_en_str($text));
/*
Array
(
[0] => a
[1] => again
[2] => Hello
[3] => is
[4] => of
[5] => PHP
[6] => test
[7] => This
[8] => World
[9] => world
)
*/
// 保留重複
print_r(split_en_str($text, false));
/*
Array
(
[0] => a
[1] => again
[2] => Hello
[3] => Hello
[4] => is
[5] => of
[6] => PHP
[7] => test
[8] => This
[9] => World
[10] => world
)
*/
?>
正則模式細節
| 模式 | 匹配內容 | 說明 |
/([a-zA-Z]+)/ | 連續英文字母 | 基本單詞提取,忽略數字、底線、連字號 |
/([a-zA-Z0-9_]+)/ | 字母數字底線 | 類程式語言識別符 |
/\b([a-zA-Z]+)\b/ | 單詞邊界 | 避免部分匹配(如 "PHP5" 不匹配 "PHP") |
/([a-zA-Z'-]+)/ | 含撇號、連字號 | 支援 "don't", "mother-in-law" |
進階:Unicode 支援(多語言單詞)
<?php
// 需 PHP 5.1+ PCRE Unicode 屬性支援
function split_unicode_words(string $str, bool $distinct = true): array {
// \p{L} 匹配任意 Unicode 字母
preg_match_all('/(\p{L}+)/u', $str, $matches);
$words = $matches[1] ?? [];
if ($distinct) $words = array_unique($words);
// 區域感知排序
setlocale(LC_COLLATE, 'zh_TW.utf8');
uksort($words, 'strcoll');
return array_values($words);
}
// 測試中英混雜
$text = "Hello 世界 PHP 程式設計 World 你好";
print_r(split_unicode_words($text));
/*
Array
(
[0] => Hello
[1] => PHP
[2] => World
[3] => 世界
[4] => 你好
[5] => 程式設計
)
*/
?>
效能優化建議
- 大量文本:考慮
mb_split() 或分塊處理,避免單次正則記憶體峰值
- 高頻呼叫:快取編譯後的正則(PHP 內部自動快取,但可用靜態變數明確控制)
- 只需計數:使用
preg_match_all() 直接取 count($matches[0]),避免建立陣列副本
常見應用場景
- 全文搜尋倒排索引建立(分詞)
- 關鍵字提取、標籤雲生成
- 內容審核:敏感詞檢測
- SEO 分析:關鍵字密度統計
- 自然語言處理前處理