PHP
<?
function how_many_lines
($width,
$string,
$options =
array()) {
if (!
is_array($options)) $options =
array();
if ($width <
1) {
trigger_error('Width should be > 0');
return false;
}
$default_options =
array(
'white_spaces' =>
array(' ',
"\t"),
'new_lines' =>
array("\r\n",
"\n"),
'force_line_breaks' =>
true,
'callback' =>
null,
'callback_params' =>
array(),
'char_widths' =>
null,
);
extract(array_merge($default_options,
$options));
if ($callback ==
null) {
if ($char_widths !=
null) {
$callback =
create_function('$char, $char_map',
'return (isset($char_map[$char]) ? $char_map[$char] : 0);');
$callback_params =
array($char_widths);
} else {
$callback =
create_function('$char',
'return 1;');
}
}
$string =
str_replace($new_lines,
"\n",
$string);
$string =
str_replace($white_spaces,
' ',
$string);
$str_length =
strlen($string);
if ($str_length >
0 &&
$string[$str_length-1] ==
"\n") {
$str_length--;
}
$sep =
-1;
$pos =
$j =
$line_length =
0;
$number_of_lines =
1;
while ($pos <
$str_length) {
$char =
$string[$pos];
if ($char ==
"\n") {
$number_of_lines++;
$pos++;
$sep =
-1;
$j =
$pos;
$line_length =
0;
} else {
if ($char ==
' ') {
$sep =
$pos;
}
$line_length +=
call_user_func_array($callback,
array_merge(array($char),
$callback_params));
if ($line_length >
$width) {
if ($sep ==
-1) {
if (!
$force_line_breaks) {
return false;
} else {
if ($pos ==
$j) { // да к тому же $pos == $j !
$pos++;
}
}
} else {
$pos =
$sep +
1;
}
$sep =
-1;
$j =
$pos;
$line_length =
0;
$number_of_lines++;
} else {
$pos++;
}
}
}
return $number_of_lines;
}
?>