How to use Regular Expressions In PHP
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 w3wiki: 2 Hello: 1
How to Count Occurrences of Each Word in Given Text File in PHP ?
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 w3wiki
Welcome to w3wiki
Hello Welcome
Contact Us