我有一個mySql數據庫我想從它的body字段只顯示包含html代碼的10個單詞,我該怎麼做,是否有任何PHP函數來做到這一點。如何僅顯示正文文本中的幾行
回答
更好的解決方案
function gen_string($string,$min=10,$clean=false) {
$string = str_replace('<br />',' ',$string);
$string = str_replace('</p>',' ',$string);
$string = str_replace('<li>',' ',$string);
$string = str_replace('</li>',' ',$string);
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max && !$clean) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return trim($r);
}
只是通過gen_string()函數
$ten = 10;
$text = strip_tags($bodyText); // remove html tags from the body text
$wordArray = str_word_count($text,2); //extract word offsets into an array
$offsetArray = array_keys($wordArray); // Convert offsets to an array indexed by word
$firstTenWords = substr($text,0,$offsetArray[$ten]-1); extract from the string between the start and tenth word
我忘了,你想拿到第10個字,但我會嘗試使用剝離字符串的一個子,並帶回了一定數目的字符。可能更容易代碼和相對相同的結果:
<?php
$start_position = 0;
$length = 30; // number of characters, not words
$suffix = "..."
// check if string is longer than limit and if so, shorten and attach suffix
if (strlen($your_text) > ($length - 3) {
echo substr(strip_tags($your_text), $start_position, $length) . $suffix;
} else {
echo $strip_tags($your_text);
}
?>
應該做的伎倆,如果你擺脫所有的格式,像換行等
當你的字段包含HTML,這是非常困難的得到有效的html - mysql不理解html。
您可以使用MySQL的substring雖然:
我建議創建這一個多列,所以你並不需要限制每個請求的話。限制將很容易做到與使用PHP:
$str = '<html>word word <b> word word word word word</b> word word word <u> word</u></html>';
$str = strip_tags($str); // strip html tags
preg_match('/^\s*+(?:\S++\s*+){1,10}/u', $str, $matches); // kohana's Text::limit_words()
$str = trim($matches[0]); // first 10 words of string
+1使用正則表達式 – 2010-06-17 15:41:27
這樣的事情可能會得心應手。
echo substr($returnedQuery, 0,10);
OP是10個單詞之後,而不是10個字符 – 2010-06-17 15:40:21
我沒有說這只是它可能派上用場的確切答案。 – 2010-06-17 15:41:40
- 1. 顯示文本幾行
- 2. 如何在TextView中顯示真正大的文本(幾個宏)?
- 3. 如何僅在IE中顯示文本
- 4. 批處理腳本僅顯示文本文件每行的幾個字
- 5. 如何在C中僅顯示文本行的特定部分#
- 6. JsqMessageViewController視圖僅顯示單行文本
- 7. 如何僅在Web瀏覽器控件中顯示網頁正文文本?
- 8. 僅顯示長文本中的JTable
- 9. 如何在rdl文件中僅粗體顯示特定文本
- 10. 如何驗證文本字段僅顯示2種文本
- 11. 在MVC中顯示幾行文字
- 12. CSS - 文本溢出:僅顯示2行文本
- 13. 僅從HTML中獲取顯示文本
- 14. 批處理文件只顯示現有文本文件中的幾行
- 15. 如何顯示從文件中讀取的正常文本
- 16. 如何顯示大量的文本行
- 17. 如何使用print_r僅顯示數組中的文本
- 18. 如何僅突出顯示UILabel中的文本 - IOS
- 19. Emacs如何僅顯示文件中光標或之前的行
- 20. 面板正文中的文本沒有顯示在行
- 21. 僅顯示文本流的MVC圖表
- 22. SVN - 僅顯示版本化的本地文件(命令行)?
- 23. 如何顯示文本文件中的隨機行?
- 24. 僅在文本框中輸入文本時顯示X按鈕
- 25. 在文本框中添加文本,僅在點擊時顯示
- 26. 如何顯示一些多行文本?
- 27. 如何在同一行顯示文本?
- 28. 如何逐行顯示文本 - Xcode
- 29. 如何在多行顯示文本?
- 30. Edittext中的文本顯示不正確
你可以指定你想要做的正是通過HTML?舉個例子吧? – 2010-06-17 15:31:28