Skip to content

Instantly share code, notes, and snippets.

@gskema
Created October 17, 2016 07:42
Show Gist options
  • Save gskema/63a285f04d6f43932c636dba1fa845ec to your computer and use it in GitHub Desktop.
Save gskema/63a285f04d6f43932c636dba1fa845ec to your computer and use it in GitHub Desktop.
Counts the number of lines in a container where character count per line is known or approximate.
<?php
/**
* Counts the number of lines in a container where character count per line is known or approximate.
* It assumes that words can be broken.
*
* @param string $text
* @param int $perLine
*
* @return int
*/
function lineCount($text, $perLine = 90)
{
$lines = 0;
$prev = 0;
$next = 0;
while (isset($text[$next]) && false !== ($next = strpos($text, "\n", $next))) {
$lines += (int)ceil(($next - $prev) / $perLine);
$prev = ++$next;
}
$l = strlen($text);
if ($prev < $l - 1) {
$lines += (int)ceil(($l - 1 - $prev) / $perLine);
}
return $lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment