如何根据单词的数量将文本拆分成行?

时间:2014-02-15 13:23:01

标签: 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实现这一目标?

2 个答案:

答案 0 :(得分:1)

使用preg_split()将句子拆分为单词数组,并使用array_chunk()将该数组拆分为多个所需长度的块:

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

答案 1 :(得分:1)

根据需要更改$ numOfWords

<?php
     $text = "The quick brown fox jumped over the lazy dog.";
     $newtext = explode(" ", $text);

     $numOfWords = 3;

     for($i=0;$i<sizeof($newtext);$i++){
        echo $newtext[$i]." ";
        if(((($i+1) % $numOfWords) == 0) && $i!=0){
            echo '<br />';
        }
     }


 ?>