php - 如何根据字数将文本分成几行?

标签 php string

<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.

Demo.

关于php - 如何根据字数将文本分成几行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798131/

相关文章:

PHP 通知 : Use of undefined constant type

c - strcat 导致字符串变空

python - 打印关键字后的 5 个字符

java - 字符串到整数的转换

html - 将字符串从 html 转换为列表

php - 如何在 Laravel 的 Controller 重定向时显示成功消息?

php - 如何在php中循环传递数组?

php - Codeception清理与依赖

php - 在 Codeigniter 上使用 HIghcharts 获取数据名称和总数

javascript - 如何删除所有其他字符串,但数组中包含 "metal"的字符串