2012-01-24 28 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'); 

编辑:添加功能例如,占文本