Answer the question
In order to leave comments, you need to log in
How to wrap a line on a space?
You need to wrap lines (write to an array) by space according to a given size of the string length.
Example:
$text = 'Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. Если вызвана статически, возвращает объект класса DOMDocument или FALSE в случае возникновения ошибки.';
class MyClass {
public $output = array();
public function text($text, $string_length){
print_r($output);
}
}
$obj = new MyClass();
$obj->text($text, 20);
Array ( [0] => Возвращает TRUE в [1] => случае успешного завершения [2] => или FALSE в случае возникновения [3] => ошибки. Если вызвана статически, [4] => возвращает объект класса DOMDocument [5] => или FALSE в случае возникновения )
class MyClass {
public $output = array();
public function text($text, $string_length){
$i = 0;
foreach(explode(' ', $text) as $val){
if(!empty($this->output[$i])){
if(iconv_strlen($this->output[$i], 'utf-8') < $string_length){
$this->output[$i] .= $val.' ';
} else {
++$i;
if(isset($this->output[$i])){$this->output[$i] .= $val.' ';}
}
} else {
$this->output[$i] = $val.' ';
}
}
print_r($this->output);
}
}
$obj = new MyClass();
$obj->text($text, 20);
Array ( [0] => Возвращает TRUE в [1] => успешного завершения [2] => FALSE в случае возникновения [3] => Если вызвана статически, [4] => объект класса DOMDocument [5] => FALSE в случае возникновения )
Answer the question
In order to leave comments, you need to log in
function stringSplit($text, $maxRowLength) {
$result = [];
$words = explode(' ', $text);
$nextRow = '';
foreach ($words as $word) {
$calculatedRow = $nextRow . ' ' . $word;
if (iconv_strlen($calculatedRow, 'utf-8') <= $maxRowLength) {
$nextRow = $calculatedRow;
} else {
$result[] = trim($nextRow);
$nextRow = $word;
}
}
$result[] = trim($nextRow);
return $result;
}
$text = 'Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. Если вызвана статически, возвращает объект класса DOMDocument или FALSE в случае возникновения ошибки.';
var_export(stringSplit($text, 25));
echo PHP_EOL;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question