我想在特定的行中打印特定的单词字符(做一些像换行一样的事情)
假设我有40个字符。
我叫Johnty,我正在吃坚果
字符长度为20。
在第一行中,我想打印20个字符,但如果它会中断单词,那么整个单词将在下一行打印。
例如,我在第一行有20个字符的长度,所以不要像这样打印:
First Line : My Name Is Johnty an
Second Line : d i am eating an Nut
相反,我想要以下输出:
First Line : My Name Is Johnty
Second Line : and i am eating an
Third Line : Nut
如何在简单的PHP中做到这一点??Thanks in Advance
wordwrap
-将字符串包装为给定数量的字符。自动换行
<?php
$text = "My Name Is Johnty and i am eating an Nut";
$newtext = wordwrap($text, 20, "<br />n");
echo $newtext;
?>
输出:My Name Is Johnty
and i am eating an
Nut
编辑1:
YES,你可以将它保存在分割字符串后的变量中。你必须使用explode()
和wordwrap()
内部的方法来做这些事情。
$strText = "My Name Is Johnty and i am eating an Nut"; //here ur string
// Wrap lines limited to 20 characters and break
// them into an array
$lines = explode("n", wordwrap($strText, 20, "n"));
var_dump($lines);
$one=$lines;
print_r($one[0]);
输出:美元[0],
My Name Is Johnty
for $one[1],
and i am eating an
通过使用wordwrap()
,您可以在单词中换行字符。
例子:
$string = "My Name Is Johnty and i am eating an Nut";
echo wordwrap($string, 20, "<br />n")
输出:My Name Is Johnty
and i am eating an
Nut
- wordwrap() in http://php.net/
.
更新:
$string = "My Name Is Johnty and i am eating an Nut";
$arr = explode(PHP_EOL, wordwrap($string, 20, "nr"));
print_r($arr);