簡體   English   中英

在很多單詞后分割html字符串

[英]Splitting html string after so many words

我有一個字符串,如果該字符串的長度大於10個單詞,我想將其分為兩部分。 第二部分將包含在其他位置,在“更多”鏈接之后。

該字符串也將包含html標簽。 例如,字符串可以是:

<p>This is just a test string with more words than the <strong>amount allow</strong> before split, blah blah blah</p>

因此,在這種情況下,我想要:

$string[0] // <p>This is just a test string with more words than</p>;
$string[1] // <p>the <strong>amount allow</strong> before split, blah blah blah</p>;

提前致謝

好吧,我遇到了同樣的問題。 我解決了這個問題,讓我的新聞撰稿人允許在其文本中使用“ [intro ... [/ intro]”-Tags)。 然后,我用正則表達式解析標簽。

如果應該在不使用特殊標簽的情況下自動進行切割,則難度會更大。 您可以使用substr()函數。 但是,那么您將在html標簽上遇到問題。 因此,我也會用類似以下內容的方法來削減它們: substr(strip_tags($text), 0, 50) 這將允許顯示50個字符,不包括html標簽。

也許這可以幫助您:)

這不是小事,但是有一個主意:

  • 逐個字符地遍歷字符串
  • 至少保留以下狀態變量:
    • $inTag –是否在標簽內
    • $inAttribute –是否在標簽屬性內(其中“>”不結束標簽)
    • $currentTagSoFar –當前標簽的所有字符。 將以“ s”開頭,然后是“ st”,“ str”等,直到“ strong”
    • $openedTags –堆棧變量,用於放置當前打開的標簽(在找到開始標簽時按下,在找到結束標簽時彈出)
    • $wordsSoFar –到目前為止找到的單詞數
    • 也許也$insideComment ,這取決於您想要多徹底
  • 當達到目標單詞數時,從堆棧中彈出標簽,然后將剩余的結束標簽添加到字符串中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM