2017-04-03 39 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