首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 正則提取字串中所有英文單詞:preg_match_all 配合 array_unique 去重排序

     編輯:PHP 相關知識

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 分析:關鍵字密度統計
  • 自然語言處理前處理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved