Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在x值中找到最后一个空字符串并换行_Php_Arrays_String_Foreach_Split - Fatal编程技术网

Php 在x值中找到最后一个空字符串并换行

Php 在x值中找到最后一个空字符串并换行,php,arrays,string,foreach,split,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($s

我有一个字符串,我想在一个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>");
}
?>

预期结果:

区分动物和动物的状态
来自无机物质的植物,包括
生长、繁殖和功能性的能力
死亡前的活动和持续变化。

这并不总是完美的(要获得更好的实现,只需搜索
wordwrap
),但通常效果良好:

echo wordwrap($str, 50, '<br>');
echo wordwrap($str,50,
);
也许您可以使用此正则表达式替换
(\s)\w*$
给我一个示例/答案,这样我就可以将其标记为正确的示例/答案。您的字符串会给出什么结果?@abracadver我添加了预期结果