2012-08-29 51 views
1

可能重複:
split a string PHP如何顯示有限的話在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這些有限的詞。但我該怎麼做呢?

+0

只是爲了確保您希望它輸出整個字符串的前15-20個字? –

+0

是的,我想顯示字符串的前15個字 – Dev

+0

http://stackoverflow.com/questions/10137819/split-a-string-php搜索之前,你問! – 2012-08-29 11:19:21

回答

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

嘗試:

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

這樣拆分文字字符串,那麼你提取所需的量:

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

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

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

?> 
+0

對不起,我錯誤地提示了建議 - 不會修剪()'只是做工作,而不是正則表達式? – moonwave99

+0

trim僅清除字符串開頭和結尾的空格。有了這個正則表達式,我想刪除兩個或更多的空格,因爲如果你不這樣做,當爆炸時你會有空字符串什麼將被視爲單詞。 – itsjavi