[Solved] How to get words frequency in text [closed]


The following code will get 2 consecutive words:

$string = 'This is a sample text. It is a sample text made for educational purposes. This is a sample text. It is a sample text made for educational purposes.';

$sanitized = $even = preg_replace(array('#[^\pL\s]#', '#\s+#'), array(' ', ' '), $string); // sanitize: only letters, replace multiple whitespaces with 1
$odd = preg_replace('#^\s*\S+#', '', $sanitized); // Remove the first word

preg_match_all('#\S+\s\S+#', $even, $m1); // Get 2 words
preg_match_all('#\S+\s\S+#', $odd, $m2); // Get 2 words

$results = array_count_values(array_merge($m1[0], $m2[0])); // Merge results and count
print_r($results); // printing

Output:

Array
(
    [This is] => 2
    [a sample] => 4
    [text It] => 2
    [is a] => 4
    [sample text] => 4
    [made for] => 2
    [educational purposes] => 2
    [It is] => 2
    [text made] => 2
    [for educational] => 2
    [purposes This] => 1
)

One improvement would be to convert the string to lowercase ?
I let the rest to you to figure out 🙂

5

solved How to get words frequency in text [closed]