![]() |
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
Method 1: Using
|
<?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
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 $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
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |