Search code examples
phpstringword-count

How do i find the occurence of words of particular number


Hello guys I have a small question that suppose I have a string as

"Hello My name is XYZ"

Now I know I can find the length of the words as "Hello" has 5 characters and "My" has 2 characters. By using following code

$text = file_get_contents('text.txt'); // $text = 'Hello my name is XYZ';
$words = str_word_count($text, 1);
$wordsLength = array_map(
function($word) { return mb_strlen($word, 'UTF-8'); },
$words
);

var_dump(array_combine($words, $wordsLength));

But what if i want to find that the number of words with length 1 is 0. The number of words with lengths 2 is 2. The number of words with length 3 is 1 and so on till number of length 10

Note- I am considering the word length till there is a space Suppose there is a date in the data like 20.04.2016 so it should show me that the number is words with length 10 is 1.

and one more thing how do I find the average length for the words in the string. Thank you in advance


Solution

  • If you use array_count_values() on the $wordsLength array it will give a count of the string lengths there are. If you use this and a template array (created using array_fill()) with the elements 1-10 and a value of 0. You will get a list of all of the word counts...

    $counts = array_replace(array_fill(1, 9, 0), 
                 array_count_values($wordsLength));
    

    will give...

    Array
    (
        [1] => 0
        [2] => 2
        [3] => 1
        [4] => 1
        [5] => 1
        [6] => 0
        [7] => 0
        [8] => 0
        [9] => 0
    )