Open In App

How to Count Occurrences of Each Word in Given Text File in PHP ?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

PHP is a server-side scripting language used for web development and offers powerful functionalities for text processing. Given a text file and want to count the occurrences of each word in it. PHP provides several approaches to achieve this.

Filename: gfg.txt

Welcome to GeeksforGeeks
Welcome to GeeksforGeeks
Hello Welcome

Method 1: Using str_word_count() and array_count_values() Functions

The str_word_count() function can be used to break down a string into an array of words. Combining this with array_count_values() allows us to count the occurrences of each word.

PHP




<?php
    
$file = file_get_contents('gfg.txt');
  
$words = str_word_count($file, 1);
  
$wordCounts = array_count_values($words);
  
foreach ($wordCounts as $word => $count) {
    echo "$word: $count\n";
}
  
?>


Output:

Welcome: 3 to: 2 GeeksforGeeks: 2 Hello: 1 

Method 2: Using Regular Expressions

Regular expressions offer more flexibility in handling different word patterns and can help clean the data by removing unwanted characters. This example uses preg_replace() function to remove non-word characters and converts all words to lowercase for case-insensitive counting.

PHP




<?php
  
$fileContent = file_get_contents('gfg.txt');
  
// Remove non-word characters
$fileContent = preg_replace('/[^\w\s]/', '', $fileContent);
  
// Convert to lowercase for case-insensitive counting
$words = str_word_count(strtolower($fileContent), 1);
  
$wordCounts = array_count_values($words);
  
foreach ($wordCounts as $word => $count) {
    echo "$word: $count\n";
}
  
?>


Output:

Welcome: 3 to: 2 GeeksforGeeks: 2 Hello: 1 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads