在x值中找到最后一个空字符串并创建新行

时间:2017-06-05 15:51:56

标签: php arrays string foreach split

我有一个字符串,我想在50长字符串的最后一个空格上创建新行。

<?php
$str = "the condition that distinguishes animals and plants from inorganic matter, including the capacity for growth, reproduction, functional activity, and continual change preceding death.";

$a = str_split($str, 50);

foreach ($a as $value) {
    $lastspace = strrpos($value, " ");
    echo chunk_split($value, $lastspace, "<br>");
}
?>

预期结果:

区分动物的条件和 来自无机物的植物,包括
增长,繁殖,功能的能力 活动,死亡前的不断变化。

1 个答案:

答案 0 :(得分:4)

它并不总是完美的(为了更好的实现,只需搜索#the-element),但这通常很有效:

wordwrap