Here's a quick and easy way to calculate the read time of any content in PHP, like the article you're reading now!
We'll start with the pure PHP example, and then look at a framework-specific solution in Laravel.
It's actually pretty easy to do thanks to the built-in str_word_count
function in PHP.
$body = ''; // the body of your article
$readTime = ceil(str_word_count($body) / 240);
Here, we're working out the word count of the article, and then choosing a words per minute speed to divide it by. Finally, we round it up.
I find it better to round up and use a slightly slower than average reading speed, particularly for technical articles where code is mixed in with words.
To get the reading time of content in Laravel, the solution is slightly easier and cleaner. We're also easily able to output the pluralised version to display.
$body = ''; // the body of your article
$readTime = ceil(str($body)->wordCount() / 240);
As you can see, the word count is the only thing that changes here, and you're free to keep the native str_word_count
function if you like.
To output the full pluralized string, here's what you'd do:
$body = ''; // the body of your article
$readTime = ceil(str($body)->wordCount() / 240);
echo $readTime . ' ' . str()->plural('minute', $readTime) . ' read';
Arguably you may not need to pluralize this, since 45 minute read time (for example), is valid.