How to find out in PHP the number of lines in a block of given width, i.e. determine the number of line breaks
or simply the number of lines the text will be split into
function GetCountLines($text, $NumSymInLine )
{
$CountLines = 0;
$len = mb_strlen($text, 'UTF-8');
if ($len > 0) $CountLines = 1;
$entry = (str_word_count($text, 2, "АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"));
$leng = 0;
foreach ($entry as $k => $v)
{
$leng = $leng + mb_strlen($v);
if ($leng > $NumSymInLine)
{
$CountLines++;
$leng = $k;
}
}
return $CountLines;
}
the functions GetCountLines and str_word_count work correctly with UTF8
NumSymInLine is the maximum number of characters per line; the function does not account for varying character widths
if you need to truncate the text while keeping a certain number of lines, that's described here
http://my-city.com.ua/forum/topic.php?f=kak-na-php-obrezat-tekst-ostavljaja-nuzhnoe-kolichestvo-strok(ostaviv-opredelennoe-chislo-perenosov)&forum=38&topic=71
Comments