如何仅显示正文中的几行

时间:2010-06-17 15:24:01

标签: php mysql string

我有一个mySql数据库我想从它的正文字段中只显示10个单词,其中包含html代码,我该怎么做,有没有任何php函数可以做到这一点。

6 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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);
 } 
 ?>

如果您要摆脱所有格式化,例如换行符等,应该可以解决这个问题。

答案 3 :(得分:0)

由于你的字段包含html,很难获得有效的html - mysql不懂html。

你可以使用mysql的substring

答案 4 :(得分: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()函数传递html

答案 5 :(得分:-1)

这样的事情可能会很方便。

 echo substr($returnedQuery, 0,10);
相关问题