例如,我有一个如下所示的字符串
$str = "What does the fox say to the elephant"
我的每行字符数限制为10。
我想在10个字符后添加新行(\ n)到单词的结尾。结果输出应该像
"What does the\n fox say to the\n elephant"
我尝试了类似下面的内容。
$str = "What does the fox say to the elephant"
echo funk($str);
function funk($s)
{
$s= explode(" ",$s);
foreach($s as $so)
{
$count += strlen($so);
if($count > 10)
{
$newstr = "$so/n ";
}
else
{
$newstr = "$so";
}
}
}
答案 0 :(得分:1)
PHP的wordwrap功能是你需要的:
<?php
$text = "A very long woooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "\n", false);
echo "$newtext\n";
更改最终参数(当前为false)将确定字符串是仅在空白处拆分还是在字符串中的任何点处拆分。