2010-06-17 23 views
1

我有一個mySql數據庫我想從它的body字段只顯示包含html代碼的10個單詞,我該怎麼做,是否有任何PHP函數來做到這一點。如何僅顯示正文文本中的幾行

+0

你可以指定你想要做的正是通過HTML?舉個例子吧? – 2010-06-17 15:31:28

回答

0

更好的解決方案

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()函數

+0

製表符,換行符,只是爲了舉幾個爲什麼你不應該喊'更好'。 – Wrikken 2010-06-17 16:19:31

+0

製表符和換行符不會在html模式下顯示。這個比較好。 – andufo 2010-06-17 16:53:32

+0

謝謝你的作品 – Saqueib 2010-06-17 17:19:02

0
$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 
0

我忘了,你想拿到第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); 
} 
?> 

應該做的伎倆,如果你擺脫所有的格式,像換行等

0

當你的字段包含HTML,這是非常困難的得到有效的html - mysql不理解html。

您可以使用MySQL的substring雖然:

1

我建議創建這一個多列,所以你並不需要限制每個請求的話。限制將很容易做到與使用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 
+0

+1使用正則表達式 – 2010-06-17 15:41:27

-1

這樣的事情可能會得心應手。

echo substr($returnedQuery, 0,10); 
+0

OP是10個單詞之後,而不是10個字符 – 2010-06-17 15:40:21

+0

我沒有說這只是它可能派上用場的確切答案。 – 2010-06-17 15:41:40