php 在长文本中自动换行-注意句子

hc2pp10m  于 2023-04-28  发布在  PHP
关注(0)|答案(1)|浏览(170)

字符串有很长的文本。如何在100个单词后自动换行而不切割单词并处理逗号和点。一个句子不应该被打破。点后只能换行。当完整文本中没有br标记时,应添加换行符。
示例:

$string = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.';

输出:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. 
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

我试过wordwrap,但它太简单了。

qybjjes1

qybjjes11#

按空格拆分字符串。在保持计数器的同时,将项逐个添加到输出中。如果计数器〉= 100,检查每个单词是否以点结尾。如果是,则输出中断并将计数器重置为0。
所以,就像这样:

<?php
  $string = 'Your chunk of. Lipsum.';

  $words = explode(' ', $string);

  echo '<p>';

  $counter = 0;
  foreach ($words as $word) {
    echo $word . ' ';
    if (++$counter >= 100) {
      if (substr($word, -1) === '.') {
        echo "</p>\n\n<p>"; // End the paragraph and start a new one.
        $counter = 0;
      }
    }
  }
  echo '</p>';

相关问题