Last active
January 17, 2021 20:54
-
-
Save pretzelhands/5175233991decd74f0e1c38f8f2d586e to your computer and use it in GitHub Desktop.
Estimate the reading time of your markdown-based articles, as detailed by Medium: https://blog.medium.com/read-time-and-you-bc2048ab620c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
const WPM = 250 | |
const READING_TIME_PER_IMAGE = 12; // seconds | |
const IMAGE_THRESHOLD = 10; // After this threshold each image counts for 3 seconds | |
function readingTimeEstimate($markdown) { | |
$markdown = strip_tags($markdown); | |
$markdown = str_replace("\n", ' ', $markdown); | |
$wordCount = str_word_count($markdown); | |
$estimatedTimeForWords = $wordCount / WPM; | |
$imageCount = preg_match_all('/!\[[\w\s]+]\(.*?\)/', $markdown); | |
// We only calculate the sum of the series for the first ten images. | |
// Everything else is overage. | |
$imageSeries = min($imageCount, IMAGE_THRESHOLD); | |
// We subtract the threshold from the image count. | |
// If it's more than 10 we'll get an overage costing 3 seconds each. | |
// If it's less than 10 we'll be calculating with 3 * 0 = 0 extra seconds | |
$imageOverage = max(0, $imageCount - IMAGE_THRESHOLD); | |
// See: https://math.stackexchange.com/a/556810 | |
$estimatedTimeForImages = $imageSeries + (READING_TIME_PER_IMAGE * $imageSeries) - (($imageSeries / 2) * ($imageSeries + 1)) + ($imageOverage * 3); | |
$readingTimeEstimate = round(($estimatedTimeForImages / 60) + $estimatedTimeForWords); | |
return match((int) $readingTimeEstimate) { | |
0 => 'Less than a minute', | |
1 => '1 minute', | |
default => sprintf('%d minutes', $readingTimeEstimate), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment