2

可能重复:
拆分字符串 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 only.than 我该怎么做?

4

4 回答 4

8
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);
于 2012-08-29T11:20:10.603 回答
3

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

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

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

}
于 2012-08-29T11:21:00.383 回答
0

尝试:

$string = "Once the Flash message ...";
$words  = array_slice(explode(' ', $string), 0, 15);
$output = implode(' ', $words);
于 2012-08-29T11:19:37.657 回答
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;
    }

?>
于 2012-08-29T11:31:23.310 回答