在文本處理、搜索索引或關鍵詞提取場景中,常需要從字符串中分離出所有單詞。本文提供一個簡潔的 PHP 函數,結合正則匹配與數組去重、排序,實現單詞提取功能。
<?php
function split_en_str($str, $distinct = true) {
// 匹配連續字母序列(單詞)
preg_match_all('/([a-zA-Z]+)/', $str, $match);
// 可選:去除重復單詞
if ($distinct) {
$match[1] = array_unique($match[1]);
}
// 按字母順序排序
sort($match[1]);
return $match[1];
}
?>
$str:待處理的字符串。$distinct:布爾值,默認 true,表示返回結果去重;設為 false 保留重復單詞。<?php
$text = "Hello world, hello PHP! World is beautiful.";
$words = split_en_str($text);
print_r($words);
// 輸出:Array ( [0] => Hello [1] => PHP [2] => World [3] => beautiful [4] => hello [5] => is [6] => world )
/([a-zA-Z]+)/ 僅匹配純字母單詞,自動過濾數字、標點、中文字符。array_unique 保留鍵名,配合 sort 重新索引並排序。關鍵詞提取、文本統計、簡易搜索引擎分詞預處理等。