You get a bonus - 1 coin for daily activity. Now you have 1 coin

How to find out in PHP the number of lines in a block of a given width, i.e. determine the number of line breaks

Practice




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
created: 2013-07-17
updated: 2026-03-10
325



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)