2012-01-24 26 views
3

我正在我的PHP網站(不是Wordpress網站)上的主索引我顯示了兩個最新的職位。事情是在描述它顯示整個文章,我發現自己需要顯示後可能35個字的限制。顯示文章摘錄,由字數限制

<?=$line["m_description"]?> 

<? 
$qresult3 = mysql_query("SELECT * FROM t_users WHERE u_id=".$line["m_userid"]." LIMIT 1"); 
if (mysql_num_rows($qresult3)<1) { ?> 
+1

什麼是你的問題,標點符號和數字?你想知道如何只顯示35條文章的文字? –

+0

是的,我想知道如何只顯示文章的35個字。 – user1167384

+0

[如何在PHP中使用substr()捕獲完整單詞,限制單詞?](http://stackoverflow.com/questions/3538130/how-to-capture-complete-words-using-substr-in -php-limit-by-word) – rdlowrey

回答

0

我有一個功能,但其他人可能會說,這不是一件好事,因爲我還是擅長PHP太(TIPS歡迎的人),但是這會給你你在找什麼,它可能需要更好的編碼,如果任何人都有建議。

function Short($text, $length, $url, $more){ 
$short = mb_substr($text, 0, $length); 

if($short != $text) { 
    $lastspace = strrpos($short, ' '); 
    $short = substr($short , 0, $lastspace); 

    if(!$more){ 
     $more = "Read Full Post"; 
    } // end if more is blank 

    $short .= "...[<a href='$url'>$more</a>]"; 
} // end if content != short 

$short = str_replace("’","'", $short); 
$short = stripslashes($short); 
$short = nl2br($short); 

} // end short function 

使用:

說你的文章內容是變量$內容

function($content, "35", "http://domain.com/article_post", "Read Full Story"); 
echo $short; 

同樣,你可以調整函數刪除$ url和$多從它,只是在...結尾處有...的摘錄。

+0

那樣? (編輯) – bowlerae

+0

@bowlerae這看起來是一個很好的起點。如果你想清理這種時髦的窗口字符(連字符,智能/雙引號,破折號,複製符號等),那麼有更多的符號不是簡單的單引號來考慮,但這是一個整體話題。此外,摘錄幾乎總是有問題,最終被截斷的HTML;解決這個問題吧! :) – Kato

9
<?php 

// just the excerpt 
function first_n_words($text, $number_of_words) { 
    // Where excerpts are concerned, HTML tends to behave 
    // like the proverbial ogre in the china shop, so best to strip that 
    $text = strip_tags($text); 

    // \w[\w'-]* allows for any word character (a-zA-Z0-9_) and also contractions 
    // and hyphenated words like 'range-finder' or "it's" 
    // the /s flags means that . matches \n, so this can match multiple lines 
    $text = preg_replace("/^\W*((\w[\w'-]*\b\W*){1,$number_of_words}).*/ms", '\\1', $text); 

    // strip out newline characters from our excerpt 
    return str_replace("\n", "", $text); 
} 

// excerpt plus link if shortened 
function truncate_to_n_words($text, $number_of_words, $url, $readmore = 'read more') { 
    $text = strip_tags($text); 
    $excerpt = first_n_words($text, $number_of_words); 
    // we can't just look at the length or try == because we strip carriage returns 
    if(str_word_count($text) !== str_word_count($excerpt)) { 
     $excerpt .= '... <a href="'.$url.'">'.$readmore.'</a>'; 
    } 
    return $excerpt; 
} 

$src = <<<EOF 
    <b>My cool story</b> 
    <p>Here it is. It's really cool. I like it. I like lots of stuff.</p> 
    <p>I also like to read and write and carry on forever</p> 
EOF; 

echo first_n_words($src, 10); 

echo "\n\n-----------------------------\n\n"; 

echo truncate_to_n_words($src, 10, 'http://www.google.com'); 

編輯:添加功能例如,佔文本