DEV Community

Hilmi Hidayat
Hilmi Hidayat

Posted on โ€ข Originally published at divisidev.com on

Estimated Reading Time using Laravel Macro

If you are building an information system that shares text-based content, you may need to add an estimated reading time for that content. Some time ago, Marcel Pociot shared a code snippet for the helper using macro in Laravel.

Here's a nice little string helper macro for @laravelphp , that gives you the estimated reading time for the given text(s).

200 is the (pessimistic) avg. reading amount of words that an adult reads per minute. pic.twitter.com/QKypiT5tnT

โ€” Marcel Pociot ๐Ÿงช (@marcelpociot) May 5, 2021

The estimated reading time can help the reader estimate how long the user can read the content to completion.

And here is the code snippet.

Str::macro('readDuration', function(...$body) {
    $totalWords = str_word_count(implode(" ", $body));
    $minutesToRead = round($totalWords / 200);

    return (int)max(1, $minutesToRead);
});

$est = Str::readDuration($post->body). ' min read';
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay