2013-10-16 38 views
1

因此,在我工作的用戶輸入一個html格式的描述,並將其添加到正在工作的數據庫中,當我拉入描述時出現問題並且將其縮短爲150個字符,並添加「...」將我的html搞亂,因爲有時候標籤會被解鎖。任何建議將是美好的PHP - 減少字符串和關閉html標記

+0

簡短的回答,因爲我的時間短。將字符串放入DOM對象中,編輯該對象的文本並重建HTML。 – TecBrat

回答

0

Here是一個類似的問題很好的答案。您必須對標籤進行計數並添加截斷的那些標籤。

僞代碼

userData = getUserInput(); 
stack = array(); 
loop (line in userData) { 
    matches = search for "<*>"; // may have multiple on one line 
    loop (match in matches) { 
     tagName = getTagNameFrom(match); 
     if ("/" is not found) { 
     push tagName on stack; 
     } else if ("/" is found) { 
     pop tagName off stack; 
     // There was an error if the stack is 
     // empty or the tagName that was popped was not 
     // the same. 
     } 
    } 
} 
foreach tagName in stack { 
    userdata += "</" + tagName + ">"; 
} 

順便說一句,你的網頁聽起來很容易受到XSS。

0
  1. 您可以使用strip_tags的和不同的標記分裂的某種組合得到公正的事件縮短到150個字符。

  2. 您可以使用稱爲省略號的css樣式。舉個例子:

.ellipsisClass { 
    width: 250px; // you MUST set a width 
    white-space: nowrap; // you MUST set nowrap 
    overflow: hidden; // you MUST set overflow to hidden 
    text-overflow: ellipsis; // and then you can use text-overflow: ellipsis 
} 
+0

一種不必要的解釋它背後的一切:P – Loko

+0

@loko我不這麼認爲,因爲如果你試圖忽略那些東西,認爲我只是把它放在那裏可愛,它將不會給你任何省略。在我看來,這是文本溢出設計的一個缺陷:省略號你必須設置三個其他的東西才能使它工作。 – miyasudokoro

0

你可以參考的解決方案的鏈接:https://github.com/dhngoc/php-cut-html-string。 如果要在切割後在字符串末尾添加「...」。你必須調整功能cutHtmlString,看到這些行代碼:

$opened_tags = array_reverse($opened_tags); 
foreach ($opened_tags as $key => $item) { 
    $act_str = $act_str . '</'.$item.'>';  
} 

更改爲

$opened_tags = array_reverse($opened_tags); 
foreach ($opened_tags as $key => $item) { 
    if ($key == 0) { 
    $act_str = $act_str . '...</'.$item.'>';  
    } else { 
    $act_str = $act_str . '</'.$item.'>';  
    }  

}