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


How to show limited words in php

可能重复:
拆分字符串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这样的限定词。那么我该怎么做呢?

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);

通过这种方式,您可以将字符串拆分为单词,然后提取所需的数量:

function trimWords($string, $limit = 15)
{
    $words = explode(' ', $string);
    return implode(' ', array_slice($words, 0, $limit));
}

尝试使用:

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

我很久以前为此创建了一个函数:

<?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;
    }
?>