如何在php中显示有限的单词

时间:2012-08-29 11:15:44

标签: php string

  

可能重复:
  split a string PHP

我是PHP的新手。我有一个像:

这样的字符串
$string="Once the Flash message has been set, I redirect the user to the form or a list of results. That is needed in order to get the flash working (you cannot just load the view in this case… well, you can but this method will not work in such case). When comparing $result TRUE or FALSE, please notice the different value for type. I am using type=message for successful messages, and type=error for error mesages.";

现在我想只显示15或20这样有限的单词。我怎么能这样做?

4 个答案:

答案 0 :(得分:5)

function limit_words($string, $word_limit)
{
    $words = explode(" ",$string);
    return implode(" ", array_splice($words, 0, $word_limit));
}

$content = 'Once the Flash message has been set, I redirect the user to the form or a list of results. That is needed in order to get the flash working (you cannot just load the view in this case… well, you can but this method will not work in such case). When comparing $result TRUE or FALSE, please notice the different value for type. I am using type=message for successful messages, and type=error for error mesages.' ; 

echo limit_words($content,20);

答案 1 :(得分:3)

这样你就可以用单词分割字符串,然后提取所需的数量:

function trimWords($string, $limit = 15)
{

    $words = explode(' ', $string);
    return implode(' ', array_slice($words, 0, $limit));

}

答案 2 :(得分:0)

尝试:

$string = "Once the Flash message ...";
$words  = array_slice(explode(' ', $string), 0, 15);
$output = implode(' ', $words);

答案 3 :(得分:0)

我之前为此创建了一个函数:

<?php
    /**
     * @param string $str Original string
     * @param int $length Max length
     * @param string $append String that will be appended if the original string exceeds $length
     * @return string 
     */
    function str_truncate_words($str, $length, $append = '') {
        $str2 = preg_replace('/\\s\\s+/', ' ', $str); //remove extra whitespace
        $words = explode(' ', $str2);
        if (($length > 0) && (count($words) > $length)) {
            return implode(' ', array_slice($words, 0, $length)) . $append;
        }else
            return $str;
    }

?>