如何在 PHP 中對字串中出現的單字進行計數和排序?

Susan Sarandon
發布: 2024-10-21 10:26:02
原創
225 人瀏覽過

How to Count and Sort Word Occurrences in a String in PHP?

對字符串中出現的單詞進行排序和計數

問題陳述:

您將被呈現包含各種單字的字串。目前的任務是確定字串中每個單字的出現頻率,並以有組織的方式顯示出來。

使用 PHP 的字數統計功能的解:

PHP 提供str_word_count() 函數,它將字串分割為單字的陣列。透過將此函數與 array_count_values() 函數結合使用,我們可以有效地統計每個單字的出現次數。

<code class="php">$str = 'happy beautiful happy lines pear gin happy lines rock happy lines pear ';
$words = array_count_values(str_word_count($str, 1));</code>
登入後複製

帶有 1 參數的 str_word_count() 函數可確保傳回單字數組。隨後,array_count_values() 取得該陣列並將其轉換為關聯數組,其中每個唯一單字作為鍵,其值代表出現的次數。

可以使用arsort( ) 函數按頻率降序列出單字:

<code class="php">arsort($words);</code>
登入後複製

要在循環中顯示排序結果,我們可以迭代排序數組並列印每個單字的計數:

<code class="php">foreach ($words as $word => $count) {
    echo "There are $count instances of $word.\n";
}</code>
登入後複製

這將產生類似於您提供的輸出:

There are 4 instances of happy.
There are 3 instances of lines.
There are 2 instances of pear.
There are 1 instances of gin.
There are 1 instances of rock.
There are 1 instances of beautiful.
登入後複製

以上是如何在 PHP 中對字串中出現的單字進行計數和排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!