使用php的Paginate长文本

时间:2017-04-03 08:00:11

标签: javascript php jquery html

我有一个长文本(超过10,000个单词)包含存储在字符串中的html标记。

并希望在考虑自动关闭打开的html标记并在不同的块中自动打开已关闭的html标记时,使用<div class="chunk"></div>包装每1000个单词。

我找到了很多解决方案,但它们取决于字符数量而不考虑自动打开/关闭html标记。

php函数wordwrap也忽略了修复html标签的问题。

模拟

<div id="long-text">
   Dynamic long text more than 10,000 words (Text contains HTML (img, p, span, i, ...etc) tags)
</div>

错误的结果

<div id="long-text">
   <div class="chunk">
      <p>Chunk 1 : first approximately 1000 words with their html tags
         <img src="image.jpg"> ## Unclosed <p> tag ##
   </div>

   <div class="chunk">
      ## The closed <p> tag of the previous chunk ## 
      </p><p>Chunk 2 : second approximately 1000 words with their html tags
      <img src="image.jpg"> </p><p> ## unclosed <p> tag ##
   </div>

   <div class="chunk">
      ## Missing open <p> tag because it was cut in the previous chunk ##
      Chunk 3 : third approximately 1000 words with their html tags</p>
   </div>
</div>

预期结果

<div id="long-text">
       <div class="chunk">
          <p>Chunk 1 : first approximately 1000 words with their html tags
             <img src="image.jpg"> </p>
       </div>

       <div class="chunk">
          <p>Chunk 2 : second approximately 1000 words with their html tags
          <img src="image.jpg"> </p>
       </div>

       <div class="chunk">
          <p>Chunk 3 : third approximately 1000 words with their html tags</p>
       </div>
    </div>

然后我可以使用javascript对结果进行分页。

搜索后,我在此处找到了接受的答案:Shortening text tweet-like without cutting links inside 剪切文本(仅从头开始)并自动关闭打开的html标签。

我尝试修改代码以自动打开已关闭的标签,如果我从文本中间剪切但不幸的是我没能完成这项工作。

我不介意是否有其他更好的解决方案根据使用(php或javascript或两者)的单词数量对长文本进行分页。

1 个答案:

答案 0 :(得分:2)

因此,我们的想法是使用JQuery通过克隆和拆分内部文本来对直接孩子进行分块。对于进一步的嵌套HTML,可能还需要更多的工作,但这只是一个开始:

function chunkText(length) {
    var words = $(this).text().split(" ");
  var res = [$(this)];
  if (words.length > br) {  
    var overflow = $(this).clone();            
    var keepText = words.slice(0,length);
    $(this).text(keepText.join(" "));
    overflow.text(words.slice(length).join(" "));    
    res = res.concat(chunkText.call(overflow, length));

    } 
  return res;
}

var br = 10; //Words to split on

$("#long-text > *").each( function () {
        var chunks = chunkText.call(this,br);
    $.each(chunks, function (i,v) {
      $("#long-text")
          .append($("<div>").addClass("chunk").append(v))
          .append($("<img>").attr("src","image.jpg")));
    });

});

基本演示: https://jsfiddle.net/o2d8zf4v/