Read Time: How to Determine Reading Duration for Any Article with a Simple PHP Function

When you're browsing through articles online, you might have seen something cool, a little note saying how long it'll take to read, like "5 minutes read" or "10 minutes read".
You can have that too on your blog, and it's pretty simple. All you need to know is how many words are there in your article.
Fortunately, PHP has a function that counts words in a string.
$content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tortor dignissim convallis aenean et tortor. Fringilla phasellus faucibus scelerisque eleifend donec pretium vulputate sapien nec. Adipiscing elit pellentesque habitant morbi tristique senectus et netus. Suspendisse potenti nullam ac tortor vitae. Neque aliquam vestibulum morbi blandit cursus risus at ultrices. Adipiscing elit ut aliquam purus. Dolor magna eget est lorem. Vitae auctor eu augue ut lectus arcu bibendum at. Consequat nisl vel pretium lectus quam id. Quisque sagittis purus sit amet volutpat consequat mauris nunc. Ut placerat orci nulla pellentesque dignissim enim.'; // Count the words. $words = str_word_count($content); // Divide by the average number of words per minute. $minutes = ceil($words / 238);
The average reader can read 238 words per minute according to statistics. Your audience might read faster or slower. So, you can adjust that number based on who's reading your articles.
TL;DR
use Carbon\CarbonInterval;
function read_time_in_minutes(string $value, bool $stripTags = false): int
{
// Count the words.
$words = str_word_count($stripTags ? strip_tags($value) : $value);
// Divide by the average number of words per minute.
return ceil($words / 238);
}
function read_time(string $value, bool $stripTags = false): CarbonInterval
{
$minutes = read_time_in_minutes($value, $stripTags);
return CarbonInterval::minutes($minutes);
}