<body>
<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;
?>
</body>
在上面的代码中,每 20 个字符 后显示一个换行符。
输出:
The quick brown fox
jumped over the lazy
dog.
而不是字符,我希望能够根据单词的数量进行拆分。例如,如果我将每行字数设置为 4,它应该输出:
The quick brown fox
jumped over the lazy
dog.
如何使用 PHP 实现此目的?
最佳答案
使用preg_split()
将句子拆分为单词数组并使用 array_chunk()
将该数组拆分为多个所需长度的 block :
$wordsPerLine = 4;
$words = preg_split('/(?<=\w)\b\s*/', $text);
$chunks = array_chunk($words, $wordsPerLine);
foreach ($chunks as $arr) {
echo implode(' ', $arr), '<br />';
}
输出:
The quick brown fox
jumped over the lazy
dog.
关于php - 如何根据字数将文本分成几行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798131/