函數功能
- 從字符串中提取所有連續字母序列 (單詞)
- 可選去重 (
$distinct=true)
- 按字母順序排序返回數組
代碼實現
<?php
/**
* 提取英文單詞
* @param string $str 輸入字符串
* @param bool $distinct 是否去重 (默認 true)
* @return array 單詞數組 (按字母序)
*/
function split_en_str(string $str, bool $distinct = true): array {
// 正則匹配連續字母 (不含數字、下劃線)
preg_match_all('/[A-Za-z]+/', $str, $matches);
$words = $matches[0] ?? [];
if ($distinct) {
$words = array_unique($words); // 保留鍵名,值去重
}
sort($words); // 重新索引並字母序排序
return $words;
}
// --- 測試 ---
$text = "Hello world! This is a test. Hello again, WORLD.";
print_r(split_en_str($text));
/* 輸出:
Array
(
[0] => Hello
[1] => This
[2] => a
[3] => again
[4] => is
[5] => test
[6] => world
[7] => WORLD
)
*/// 注意:默認區分大小寫。如需不區分,預處理 strtolower 或正則 /[a-z]+/i
?>
進階增強版
<?php
function extractWords(string $str, array $options = []): array {
$opts = array_merge([
'distinct' => true,
'case_sensitive'=> false, // 不區分大小寫
'min_length' => 1, // 最小長度
'max_length' => 0, // 0=不限制
'sort' => 'alpha', // alpha|length|frequency
'allow_digits' => false, // 是否允許數字 (單詞邊界)
], $options);
$pattern = $opts['allow_digits'] ? '/[A-Za-z0-9]+/' : '/[A-Za-z]+/';
if (!$opts['case_sensitive']) $str = mb_strtolower($str, 'UTF-8');
preg_match_all($pattern, $str, $m);
$words = $m[0] ?? [];
if ($opts['min_length'] > 1) $words = array_filter($words, fn($w) => mb_strlen($w) >= $opts['min_length']);
if ($opts['max_length'] > 0) $words = array_filter($words, fn($w) => mb_strlen($w) <= $opts['max_length']);
if ($opts['distinct']) $words = array_unique($words);
switch ($opts['sort']) {
case 'length': usort($words, fn($a,$b) => strlen($a) <=> strlen($b)); break;
case 'frequency': $freq = array_count_values($words); arsort($freq); $words = array_keys($freq); break;
default: sort($words, SORT_STRING | SORT_FLAG_CASE); // 字母序,不區分大小寫
}
return array_values($words);
}
// 使用
$text = "The quick brown fox jumps over the lazy dog. The dog was lazy.";
print_r(extractWords($text, ['case_sensitive'=>false, 'sort'=>'frequency', 'min_length'=>3]));
/* 高頻優先: the, dog, lazy, quick, brown, fox, jumps, over, was */
?>
應用場景
- 全文搜索倒排索引構建 (分詞第一步)
- 關鍵詞提取、標簽雲生成
- 文本統計分析 (詞頻 TF-IDF 前置)
- 敏感詞過濾預處理
- SEO 關鍵詞密度分析
性能提示
preg_match_all 速度極快,百萬字符級字符串毫秒級完成。
- 大文本建議分塊處理或使用
XMLReader 流式讀取配合正則。
- 中文分詞**不能**用此方法,需結巴分詞、SCWS、THULAC 等專用分詞器。