在长文本中自动换行 - 照顾句子
Posted
技术标签:
【中文标题】在长文本中自动换行 - 照顾句子【英文标题】:Make auto line breaks in a long text - take care of sentences 【发布时间】:2016-04-08 07:33:30 【问题描述】:字符串有很长的文本。如何在 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 只是印刷和排版行业的虚拟文本。自 1500 年代以来,Lorem Ipsum 一直是行业的标准虚拟文本,当时一位不知名的印刷商采用了一种类型的厨房并将其加扰以制作一本类型样本书。它不仅经历了五个世纪,而且经历了电子排版的飞跃,基本保持不变。
它在 1960 年代随着包含 Lorem Ipsum 段落的 Letraset 表的发布而流行起来,最近随着桌面出版软件(如 Aldus PageMaker)的推出,包括 Lorem Ipsum 的版本。Lorem Ipsum 只是印刷和排版行业的虚拟文本。自 1500 年代以来,Lorem Ipsum 一直是行业的标准虚拟文本,当时一位不知名的印刷商采用了一种类型的厨房并将其加扰以制作一本类型样本书。
它不仅经历了五个世纪,而且经历了电子排版的飞跃,基本保持不变。它在 1960 年代随着包含 Lorem Ipsum 段落的 Letraset 表的发布而流行起来,最近还随着 Aldus PageMaker 等桌面出版软件(包括 Lorem Ipsum 的版本)而普及。
我试过wordwrap
,但是太简单了。
【问题讨论】:
用空格分割字符串。在保留计数器的同时将项目一一添加到输出中。如果计数器 >= 100,检查每个单词是否以点结尾。如果是,则输出中断并将计数器重置为 0。 【参考方案1】:用空格分割字符串。在保持计数器的同时将项目一一添加到输出中。如果计数器 >= 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>';
【讨论】:
我改变了 counter = 0;到 $counter = 0;它完美无缺。谢谢@GolezTrol以上是关于在长文本中自动换行 - 照顾句子的主要内容,如果未能解决你的问题,请参考以下文章