2011-10-21 7 views
0

基本的には、指定された文字列から固定数の単語をどのように出力できるかを知りたい。または、もし私のクエリが$ data4によって参照されるフィールドに限られた数の単語を格納する方法があれば。以下の例では、変数$ data4の固定数を印刷していますが、切り詰められた単語はありません。文字列から固定数の単語/ tkensを出力する

<? 
$sysquery4 = mysql_query("SELECT * FROM content WHERE sid='59' AND title!='' ORDER BY id DESC LIMIT 4") or die(mysql_error()); 

while($data4 = mysql_fetch_array($sysquery4)) { 
    $year = substr($data4['date'], 0, 4); 
    $month = substr($data4['date'], 5, 2); 
    $day = substr($data4['date'], 8, 2); 
?> 
<div class="post"> 

    <h2> 
    <? echo $data4['title']; ?> 
    </h2> 
    <span class="news_date"><? echo date('F j, Y', mktime(0,0,0,$month,$day,$year)); ></span><br /> 
    <? echo substr($data4['content'], 0,180) ;echo $lnk="... more"; ?> 

</div> 
<? } ?> 
+0

同様の質問は何度も尋ねられます。下記の回答をご確認ください。彼らはあなたの問題を解決するのに役立ちます。 http://stackoverflow.com/search?q=php+first+words –

答えて

2

あなたは次のスニペット(未テスト)でこれを解決することができます:

function limitWords($string, $num_words){ 
    //Pull an array of words out from the string (you can specify what delimeter you'd like) 
    $array_of_words = explode(" ", $string); 

    //Loop the array the requested number of times and build an output, re-inserting spaces. 
    for ($i = 1; $i <= $num_words; $i++) { 
     $output .= $array_of_words[$i] . " "; 
    } 
    return trim($output); 
} 

EDITは:その厄介な最後の追加スペースを取り除くために、最終的な出力の周りのトリムを追加しました。

関連する問題