This is the Second and Last Part in Estimated Reading Time series. Take a look at the Part 1 if you don't know the basic functions. If you know them, skip Part 1.
Learn to Implement Estimated Reading Time using PHP Part 1: The Basics
Let's move forward form the part 1 now. Let's say we have we have our whole blog post in a variable named as $article. In most blog websites, that's what they do. They store the whole story in the database and then retrieve init to a variable.
Take a look at the DEMO link provided at the end of this article and see what we have in the variable $article.
Now the whole blog post has many <p> tags which we don't want to count in our reading time as users won't see them. So we will remove them using the strip_tags function as discussed in the Part 1.
strip_tags($post);
The code above will remove all HTML tags from out blog post. Now, we can go ahead and count the words. Let's do it.
$article = str_word_count(strip_tags($post));
In the code above I am counting the value after removing the tags and we can write down both of those function like that. Also, I am storing the word count in the same variable $article.
After that we will need to add an mathematical equation to count the time. Now, we have to assume the words per minute which is generally 200 to 250 per minute for an average person on most of the blogs. I am going to use 250 words per minute in our calculation.
$EstTimeToRead=round($article/250);
Now if we use the $article/250 as it is and store in the variable then it would give us the float value but we want to round it up to the nearest decimal point so I have used round function.
That's it. We have a small counter now which will show the users time to read.
Extras
Now this part is not necessary as it's up to you how you want to display the time on the article.
If you choose to display like "1 Min Read" or "2 Min Read", then there is no issue in printing the $EstTimeToRead variable directly using echo statement.
But if you want to print the word "Minute" in it then you have to add a simple IF ELSE condition in your code as follows.
if($EstTimeToRead <=1){
$EstTimeToRead = "1 Minute read";
}
else{
$EstTimeToRead = $EstTimeToRead . " Minutes Read";
}
After adding above few lines of code into your PHP script, you'll be able to print the word "Minute" when there is just 1 minute and "Minutes" when there are 2 or more minutes to read.
reading time word count