萬盛學電腦網

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

PHP 獲取字符串中所有單詞的高效方法

前言

在文本處理、搜索索引或關鍵詞提取場景中,常需要從字符串中分離出所有單詞。本文提供一個簡潔的 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 重新索引並排序。
  • 函數返回已排序的數組,便於後續展示或存儲。

適用場景

關鍵詞提取、文本統計、簡易搜索引擎分詞預處理等。

copyright © 萬盛學電腦網 all rights reserved