Skip to content

Instantly share code, notes, and snippets.

@Soladiem
Created February 1, 2021 17:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Soladiem/b57425738e0a70ff8e1d10be74ec1c33 to your computer and use it in GitHub Desktop.
Save Soladiem/b57425738e0a70ff8e1d10be74ec1c33 to your computer and use it in GitHub Desktop.
Подсчет времени чтения статьи (PHP)
/**
* Class readTimeEstimate
* Подсчет времени чтения статьи
*/
class readTimeEstimate
{
/**
* Средняя скорость чтения слов в минуту
*/
const WORDS_PER_MINUTE = 200;
const STR_MINUTE = 'мин.';
const STR_SECOND = 'сек.';
private $minutes;
private $seconds;
/**
* readTimeEstimate constructor.
* @param string $str
*/
function __construct(string $str)
{
$wordCount = $this->wordCount(strip_tags($str));
$this->minutes = floor($wordCount / static::WORDS_PER_MINUTE);
$this->seconds = floor($wordCount % static::WORDS_PER_MINUTE / (static::WORDS_PER_MINUTE / 60));
}
/**
* @return string
*/
public function __toString(): string
{
return ($this->minutes == 0) ? $this->seconds . ' ' . static::STR_MINUTE
: $this->minutes . ' ' .
static::STR_MINUTE . ', ' .
$this->seconds . ' ' .
static::STR_SECOND;
}
/**
* @return float
*/
public function getMinutes(): float
{
return $this->minutes;
}
/**
* @return float
*/
public function getSeconds(): float
{
return $this->seconds;
}
/**
* @param string $str
* @return int
*/
protected function wordCount(string $str): int
{
$v = preg_split('/\W+/u', $str, -1, PREG_SPLIT_NO_EMPTY);
return count($v);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment