2012-12-19 34 views
0

假設我們有一個字符串patterns also provide us a common vocabulary to describe solutions如何substr()字符串到一定的長度,但直到最後的空間?

我們substr()這個字符串,所以我們有patterns also provide us a common vocabulary to desc

如何將最後一個字符串剪切爲patterns also provide us a common vocabulary to

我的辦法是:

$text = mb_substr($new['text'], 0, 100); 

if(mb_substr($text, -1) != ' ') { 

    $text_expl = explode(' ', $text); 

    $text = implode(' ', array_splice($text_expl, 0, -1)) . ' ...'; 

} 

有什麼更好?

也許regualr表達式或一些PHP內置函數可以做類似的事情?

+1

也許在另一篇文章謊言你的解決方案: http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-toa-a-某些用戶號碼的-恰拉 – andrew

回答

2

此找到最後一個空白,並採取子

$text = mb_substr($new['text'], 0, 100); 
$i = mb_strrpos($text, ' '); 
if ($i !== false) 
    $text = mb_substr($text, 0, $i); 
2

我會用這一個:

if (preg_match('/^.{1,26}\b/s', $str, $match)) 
{ 
    echo $line=$match[0]; 
} 

這截斷文本你想要的方式。另外,當你指定更多的字符時,實際上在字符串中,它只是簡單地給你回整個字符串。這是期望的結果。

以下方法也適用,但在字符串中的字符少於指定字符時會出現錯誤。

// Needs more than 260 characters in $str 
echo substr($str, 0, strpos($str, ' ', 260)); 

所以,既然你需要包裝,在一個if聲明反正檢查$str的長度,我會去的第一個選項。

相關問題