Created
February 1, 2021 17:01
-
-
Save Soladiem/b57425738e0a70ff8e1d10be74ec1c33 to your computer and use it in GitHub Desktop.
Подсчет времени чтения статьи (PHP)
This file contains 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
/** | |
* 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