What are some common pitfalls when using PHP to count the occurrences of words in a text file?

One common pitfall when using PHP to count the occurrences of words in a text file is not properly sanitizing the input. This can lead to inaccurate results or security vulnerabilities. To solve this issue, it is important to clean the text data before counting the occurrences.

<?php
// Read the text file
$text = file_get_contents('sample.txt');

// Sanitize the text by removing special characters and converting to lowercase
$text = preg_replace('/[^a-zA-Z0-9\s]/', '', $text);
$text = strtolower($text);

// Split the text into an array of words
$words = str_word_count($text, 1);

// Count the occurrences of each word
$wordCount = array_count_values($words);

// Output the word count
print_r($wordCount);
?>