Sorting and Counting Word Instances in a String with PHP
To sort and count instances of words in a given string in PHP, consider leveraging the following techniques:
<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)); print_r($words);</code>
This code will output the following array:
Array ( [happy] => 4 [beautiful] => 1 [lines] => 3 [pear] => 2 [gin] => 1 [rock] => 1 )
<code class="php">arsort($words); print_r($words);</code>
This will result in the following sorted array:
Array ( [happy] => 4 [lines] => 3 [pear] => 2 [rock] => 1 [gin] => 1 [beautiful] => 1 )
The above is the detailed content of How to Sort and Count Word Instances Efficiently in PHP?. For more information, please follow other related articles on the PHP Chinese website!