萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 字串單詞擷取去重:preg_match_all、array_unique、排序實作

函式實作

<?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] 第一群組
  • 若需支援 Unicode 字母(含中文),改用 /(\p{L}+)/u

擴充功能

支援 Unicode 字母(含中文)

function 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

copyright © 萬盛學電腦網 all rights reserved