<?php
/**
* 從字串擷取英文單詞,可選去重與排序
*
* @param string $str 輸入字串
* @param bool $distinct 是否去重,預設 true
* @return array 單詞陣列
*/
function splitEnStr(string $str, bool $distinct = true): array {
// 匹配連續英文字母
preg_match_all('/([a-zA-Z]+)/', $str, $matches);
$words = $matches[1] ?? [];
if ($distinct) {
$words = array_unique($words);
}
sort($words); // 字母序排序
return array_values($words); // 重建索引
}
// 測試
$str = 'word,word,world,cup';
print_r(splitEnStr($str));
/*
Array
(
[0] => cup
[1] => word
[2] => world
)
*/
?>
/([a-zA-Z]+)/:捕獲群組匹配一個以上英文字母preg_match_all 回傳多維陣列,$matches[0] 完整匹配,$matches[1] 第一群組/(\p{L}+)/ufunction splitWords(string $str, bool $distinct = true): array {
preg_match_all('/(\p{L}+)/u', $str, $matches);
$words = $matches[1] ?? [];
if ($distinct) $words = array_unique($words);
sort($words, SORT_LOCALE_STRING); // 當地語系排序
return array_values($words);
}
function splitUniqueKeepOrder(string $str): array {
preg_match_all('/([a-zA-Z]+)/', $str, $matches);
return array_values(array_unique($matches[1])); // 不排序
}
function wordFrequency(string $str): array {
preg_match_all('/([a-zA-Z]+)/', strtolower($str), $matches);
return array_count_values($matches[1] ?? []);
}
// ['word'=>2, 'world'=>1, 'cup'=>1]
str_word_count() 內建函式(僅 ASCII)array_unique() 內部使用雜湊表,O(n) 複雜度preg_match_all原始來源:www.111cn.net