How to Count The Sub String from a .txt file using PHP

By Saruque Ahamed Mollick

Hello everyone, here I am again with a small piece of PHP code. If you are looking for the PHP code to Count Sub-string from a text file using PHP you are at the right place.
This code is very helpful as in many cases it has been seen that developers need to count the substring from a text file to achieve some particular goal.

Get random text by line number from a text file in PHP



 

PHP code to get the number of a particular substring from a text file

<?php
$count = 0;
$myText = "filename.txt";
$fh = fopen($myText, 'r');
while(!feof($fh)){
    $fr = fread($fh, 8192);
    $count += substr_count($fr, 'yourstring');
    echo $count;
}
fclose($fh);
?>

That above code will easily print the number of a particular substring from your desired text file.

How To Read A Text File Line By Line In PHP?

 

 

Explanation of this code

$count is the variable we set to zero.
It is initialized with 0 and it is used to hold the number of substrings found in your text file.

$myText variable is taken to hold the path value with the file name.
if your text file is residing in your current path then just mention the file name or in other cases, you may add the file name with the proper path.

 

$fh = fopen($myText, 'r');

now does it means?

fopen() function in PHP is used to open a file as well as it can also be used to create a file. I know its strange to know but in PHP you can use the same function to get both tasks done.

here we are using it to open our file. Now, what are those parameters?¬†‘r’ is used to open it in reading mode.

 

while(!feof($fh)){
    $fr = fread($fh, 8192);
    $count += substr_count($fr, 'yourstring');
    echo $count;
}

now we started a while loop that will continue reading the file until reaches EOF that means, end-of-file.

fread($fh, 8192);

here 8192 is the size in byte.

and $count will be incremented by 1 each time it will find your desired substring that you want to be counted.

 

$count += substr_count($fr, 'yourstring');

replace yourstring with your desired substring that you wanna count.

Get random word from English dictionary in PHP tutorial

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *