2

重複の可能性:
文字列を分割する PHP

私はPHPの初心者です.iは次のような文字列を持っています:

$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

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

私はこれのために以前に関数を作成しました:

<?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 に答える
0

試してみてください:

$string = "Once the Flash message ...";
$words  = array_slice(explode(' ', $string), 0, 15);
$output = implode(' ', $words);
于 2012-08-29T11:19:37.657 に答える