/** * Class ReadingTime */ class ReadingTime { /** * Средняя скорость чтения слов в минуту */ const WORDS_PER_MINUTE = 200; const STR_MINUTE = 'мин.'; const STR_SECOND = 'сек.'; private $minutes; private $seconds; /** * ReadingTime 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); } }
ReadingTime Object ( [minutes:ReadingTime:private] => 1 [seconds:ReadingTime:private] => 49 )
Как использовать
$readingTime = new ReadingTime($arResult['DETAIL_TEXT'] ?: $arResult['PREVIEW_TEXT']); echo $readingTime;