0
I’m performing a line break without using the function wordwrap()
.
I will receive a string with the text, and an int with the allowed character length per line as parameter. I’ll have to cut that string, then insert it into an already cut vector.
But when I enter into the array, I end up with a blank space for each row of the array, for example:
Array(0)=> 'eu irei '
Array(1)=> 'ser '
When it was meant to be:
Array(0)=> 'eu irei'
Array(1)=> 'ser'
This generates an error when comparing with the test. How do I remove this blank at the end of each line?
class Resolution implements TextWrapInterface {
public function textWrap(string $text,int $length):array {
//local variables
$words=explode(" ",$text); //separate the text into words
$arr=array(); //array used for return
$string=" ";
$limit=$length; //limit of characters per line
$line=0;//array line
for($i = 0; $i < count($words); $i++){
$string = $words[$i]." ";
if((strlen($words[$i])>$length)){
//cut the world and print the remaining letters on the next line
$this->cutWord($arr,$words[$i],$limit,$length,$line);
}else
if($limit>=strlen($string)){
//add the word in array line
$arr[$line]=(array_key_exists($line,$arr))?$arr[$line].$string:$string;
//subtract the limit with the quantity of characters
$limit-=strlen($string);
}else
if($limit<strlen($string)){
//line++ for inserting the string on a next index
$line++;
$limit=$length;
//add the word on array line
$arr[$line]=$string;
//subtract the limit with the quantity of characters
$limit-=strlen($string);
}
}
return $arr;
print_r($arr);
}
//and then I've got a cutWord function
private function cutWord(&$array,$word,&$limit,$length,$index){
for($i = 0; $i < strlen($word); $i++){
//verify if the index doesn't have any words in
if(($limit!=$length)&&($i==0)){
$index++; // jump an array line
$limit=$length; //limit receives starting value
}
//verify if the limit is > 0
if($limit<=0) {
$index++;
$limit=$length; //limit receives starting value
}
//add the letter in the array index concatenating with the previous
$array[$index]=(array_key_exists($index,$array))?$array[$index].$word[$i]:$word[$i];
$limit--;
}
$array[$index]=$array[$index]." ";
}
I implemented rtrim in the as-sent code, and it printed the string with no space, only in the first index of the array, why is it? The concept is right.
– Apprentice345
@Apprentice345 Probably because it is not being applied in the right place, that I did not interpret its whole code from top to bottom. Try putting the
rtrim
within theif($limit<strlen($string)){
and before the$line++
, as follows:$arr[$line] = rtrim($arr[$line]);
. If thertrim
is applied word by word, will remove you all the spaces that is not what you want, and probably what is happening.– Isac
It worked, it worked, thank you very much!
– Apprentice345