A
A
Arx7772015-11-24 17:40:38
PHP
Arx777, 2015-11-24 17:40:38

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);

should get:
Array ( [0] => Возвращает TRUE в [1] => случае успешного завершения [2] => или FALSE в случае возникновения [3] => ошибки. Если вызвана статически, [4] => возвращает объект класса DOMDocument [5] => или FALSE в случае возникновения )

I solved it this way:
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);

But the result is not correct:
Array ( [0] => Возвращает TRUE в [1] => успешного завершения [2] => FALSE в случае возникновения [3] => Если вызвана статически, [4] => объект класса DOMDocument [5] => FALSE в случае возникновения )

Disappears starting from array[1].
Those. should be: [0] => Returns TRUE in [1] => CASE success
AND the word CASE is lost and end is inserted instead
.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Леша Киселев, 2015-11-24
@Arx777

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;

S
Sushkov, 2015-11-24
@Sushkov

php.net/manual/ru/function.chunk-split.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question