Skip to content

Instantly share code, notes, and snippets.

@tonylegrone
Created October 16, 2014 04:28
Show Gist options
  • Save tonylegrone/22fb7f340ecf754430d7 to your computer and use it in GitHub Desktop.
Save tonylegrone/22fb7f340ecf754430d7 to your computer and use it in GitHub Desktop.
<?php
/**
* Calculates approximate reading time in minutes.
*
* @param (string) $str
* The string of words to calculate reading time on.
* @param (int) $words_per_minute
* The words per minute to divide the time by. Defaults to 270.
* @return (string)
* The reading time in minutes.
*/
function calculate_reading_time($str, $words_per_minute = 270) {
$words = str_word_count(strip_tags($str));
$words_per_second = $words_per_minute / 60;
$reading_time_seconds = $words / $words_per_second;
$reading_time_minutes = round($reading_time_seconds / 60);
if ($reading_time_minutes > 0) {
$reading_time = $reading_time_minutes . ' min';
}
else {
$reading_time = 'Less than a minute';
}
return $reading_time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment