2012-01-13 66 views
3

編輯:關鍵是要獲取前200個字符並關閉所有打開的標記。獲取字符串的前200個字符,而不會在末尾打破HTML標記


我目前從其他網站通過DOM對象(其他網站沒有RSS)加載文章。我想使該文章的「預覽」,但這裏是我的問題:

  1. 我不控制文章是怎麼寫的,所以它似乎永遠是在第二TR的表內(他們使用CMS,它很混亂 - 請參閱下面的示例)。

  2. 他們有很多HTML標籤,我不想留下一個打開。

  3. 我需要保持HTML格式,我知道它很醜,但它完全適合我的頁面。

不是我的代碼(在法國不好意思):

<table> 

<TR > 

<TD class='Normal' valign="top" colspan="2" style="padding-bottom:15px;">13-01-2012 <b>Water-polo – Championnat pan-pacifique<b ></TD> 

</TR><TR > 

<TD class='Normal' valign="top"><span class="HeadTitleNews"> Les Canadiennes disputeront le bronze aux Chinoises</span> <img src='http://www.sportcom.qc.ca/Portals/0/2011WaterpoloF.jpg' width='165' align='right' class='imgAnnouncementCss'><div style="margin: 0in 0in 0pt"><span style="font-family: Tahoma; font-size: 10pt">Montr&eacute;al, 13 janvier 2012 (Sportcom) &ndash; L&rsquo;&eacute;quipe f&eacute;minine canadienne de water-polo a remport&eacute; une victoire &eacute;crasante de 19-3 face au Br&eacute;sil, vendredi, au Championnat pan-pacifique de Melbourne, en Australie. Les Canadiennes se sont ainsi assur&eacute;es de participer au match pour la m&eacute;daille de bronze contre les Chinoises. </span></div> 

<div style="margin: 0in 0in 0pt">&nbsp;</div> 

<div style="margin: 0in 0in 0pt"><span style="font-family: Tahoma; font-size: 10pt">La Montr&eacute;alaise <strong>Sophie</strong></span><strong><span style="font-family: Tahoma; font-size: 10pt"> Baron-La Salle</span></strong><span style="font-family: Tahoma; font-size: 10pt"> a marqu&eacute; quatre buts dans la victoire. </span></div> 

<div style="margin: 0in 0in 0pt">&nbsp;</div> 

感謝。

+0

我很困惑,正是你想要的。你是否想要取第一個200個字符,除了在第一個未封閉的HTML標記之後忽略所有內容?或者是否希望取得所有前200個字符,然後爲所有打開的標記添加結束標記? – 2012-01-13 20:29:22

+0

@BrooksMos從我的解釋看來,OP似乎希望獲得純文本的前200個字符,但後來添加HTML標記以保留格式。 – 2012-01-13 20:32:26

+0

sry如果我不清楚,第二個選項,獲得前200個字符並關閉標籤。 – 2012-01-13 20:33:00

回答

5
<?php 
$your_string_without_tags = strip_tags($your_string); 
$your_200_char_string = substr($your_string_without_tags, 0, 200); 
?> 

Close open HTML tags in a string

+1

http://stackoverflow.com/questions/3810230/ PHP-如何對近距離開HTML標籤功能於一個字符串 – dyelawn 2012-01-13 20:47:21

-1

您可以使用strip_tags函數刪除所有html標記,然後按照您的意願使用它。

+0

如果我不清楚,第二個選項,獲得前200個字符並關閉標籤。 – 2012-01-13 20:34:38

+0

這......實際上並不是一個答案,因爲如果要**保留** html標籤並關閉它們,而不是刪除**它們,那麼這個點就可以了 – 2016-03-07 16:11:06