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:
$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);
This code will output the following array:
Array ( [happy] => 4 [beautiful] => 1 [lines] => 3 [pear] => 2 [gin] => 1 [rock] => 1 )
arsort($words);
print_r($words);
This will result in the following sorted array:
Array ( [happy] => 4 [lines] => 3 [pear] => 2 [rock] => 1 [gin] => 1 [beautiful] => 1 )
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3