Smarter word-wrap in PHP for long words?

前端 未结 5 1485
無奈伤痛
無奈伤痛 2020-12-05 18:53

I\'m looking for a way to make word-wrap in PHP a bit smarter. So it doesn\'t pre-break long words leaving any prior small words alone on one line.

Let\'s say I have

5条回答
  •  鱼传尺愫
    2020-12-05 19:44

    How about

    $string = "hello! heeeeeeeeeeeeeeereisaverylongword";
    $break = 25;
    
    echo implode(PHP_EOL, str_split($string, $break));
    

    Which outputs

    hello! heeeeeeeeeeeeeeere                                                                                                                                                           
    isaverylongword
    

    str_split() converts the string to an array of $break size chunks.

    implode() joins the array back together as a string using the glue which in this case is an end of line marker (PHP_EOL) although it could as easily be a '
    '

提交回复
热议问题