2017-04-03 34 views
1

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

并且想要用<div class="chunk"></div>包装每1000个单词并考虑自动关闭已打开的html标签并自动在不同的块中打开已关闭的html标签。

我发现很多解决方案,但它们取决于字符的数量,不考虑自动打开/关闭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

XY问题,为什么你有一个10K的工作长文本? – madalinivascu

+0

数据库存储文档和数据表,每个文档都有3k个单词,有些则有10k个单词。 – semsem

+1

一个解决方案将加载所有10k字,并使用JS显示只有一部分使用以太滚动或无限滚动类型的实现 – madalinivascu

回答

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/

+0

谢谢@apokryfos的帮助。 如果我没有找到更好的解决方案,我会做这一个。 – semsem