使用PHP或javascript在中每隔2500个字符包装文本以进行分页
我有一长串文字。 我想把这个文本的每2500个字符包装成一个
这样就可以对它进行分页。
以下不起作用:
//replace 2500 for 5 for purpose of this example $text="sfdkjas;fakska;ldjk"; $text=wordwrap($text, 5, '');
输出:
sfdkjas;fakska;ldjk
显然我需要结束
标签来使这项工作。
有没有人对PHP或Javascript / jQuery有这个建议?
只需添加
然后?
$text = '' . wordwrap($text, 5, '') . '';
但是,使用javascript可以做得更好:您可以根据查看者的屏幕大小进行分页 。
只需将您的HTML设置为:
...
为页面添加一些css:
#target { white-space: pre-wrap; /* respect line breaks */ } .individualPage { border: 1px solid black; padding: 5px; }
然后使用以下代码:
var contentBox = $('#target'); //get the text as an array of word-like things var words = contentBox.text().split(' '); function paginate() { //create a div to build the pages in var newPage = $(''); contentBox.empty().append(newPage); //start off with no page text var pageText = null; for(var i = 0; i < words.length; i++) { //add the next word to the pageText var betterPageText = pageText ? pageText + ' ' + words[i] : words[i]; newPage.text(betterPageText); //Check if the page is too long if(newPage.height() > $(window).height()) { //revert the text newPage.text(pageText); //and insert a copy of the page at the start of the document newPage.clone().insertBefore(newPage); //start a new page pageText = null; } else { //this longer text still fits pageText = betterPageText; } } } $(window).resize(paginate).resize();
这将与PHP解决方案结合使用,如果禁用javascript,则提供向后兼容性。
这就是我这样做的方式:
$out = ''; $text = str_split($text, 2500); foreach($text as $t){ $out .= "".$t.""; } echo $out;
编辑:这将打破单词,所以坚持使用wordwrap()
。 :d
只需在开头添加一个开头div,在结尾添加一个结束div,并在每次迭代开始时关闭div。
$div = ''; $text = $div . wordwrap($text, 5, "$div") . '';
在Javascript中,内置解决方案并不是那么好。
var s = text, div = ""; while(text.length > 5) { s = text.slice(0, 5) + "" + div; text = text.slice(5); } s = div + s + "";
只是为了好玩 – 这是一个相当丑陋的JavaScript RegExp,它将对文本进行分页并尽量不破坏文字。 我不确定它在大量文本上的表现如何。
var text = .... // Grab 2500 (or slightly more if it doesn't exactly end on a word boundary) // characters, or less than 2500 if it's at the end of the string. text = text.replace(/(((.|\n){2500,2520}?\b)|((.|\n){1,2499}(?!.)))/mg, '$1')
的jsfiddle