2010-06-10 310 views
38

我正在尋找一種方法來限制在PHP中的字符串,並加上...在最後,如果字符串太長。限制字符串長度

+0

您可能會發現['S($ STR) - >截斷($長度)'](https://github.com/delight-im/PHP-Str/ blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L233)甚至['s($ str) - > truncateSafely($ length)'](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc /src/Str.php#L246)很有幫助,在[這個獨立的庫](https://github.com/delight-im/PHP-Str)中找到。 – caw 2016-07-27 01:01:21

回答

90

您可以使用類似於下面的東西:

if (strlen($str) > 10) 
    $str = substr($str, 0, 7) . '...'; 
+0

我想你不認爲他可能會跳過他的作業閱讀任務。 – dlamblin 2010-06-10 23:43:13

+0

對不起,我沒有考慮到這一點。作業的規則是什麼? 哦,等等,我只是注意到,我的代碼甚至不能正常工作;) – bramp 2010-06-10 23:47:18

+2

這只是一個社區規則:http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer -homework-questions – dlamblin 2010-06-11 00:01:42

0

要截斷由最高限額提供的字符串不破壞一個字使用:

/** 
* truncate a string provided by the maximum limit without breaking a word 
* @param string $str 
* @param integer $maxlen 
* @return string 
*/ 
public static function truncateStringWords($str, $maxlen) 
{ 
    if (strlen($str) <= $maxlen) return $str; 

    $newstr = substr($str, 0, $maxlen); 
    if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " ")); 

    return $newstr; 
} 
13

PHP 4.0.6 ,對於同樣的事情

功能MB功能 _ strimwidth可用於您的要求

<?php 
echo mb_strimwidth("Hello World", 0, 10, "-yahooo!-"); 
//Hello W-yahooo!- 
?> 

它有更多的選擇,雖然,這裏是這個mb_strimwidth

文檔
+0

wordwrap()函數也可以是有用的:http://www.w3schools.com/php/func_string_wordwrap.asp – 2016-05-04 16:49:05

+0

但個人而言,我更喜歡使用:$ s = preg_replace('/ \ s +?(\ S +)?$ /','',substr($ s,$ START,$ LIMIT)); – 2016-05-04 17:56:43

+2

@CyrilJacquart更好地避免使用正則表達式,只要它不是必需的。 – 2016-06-10 10:30:59

0

以另一種方式來限制PHP中的字符串並添加閱讀文本或像'...'使用以下代碼

if (strlen(preg_replace('#^https?://#', '', $string)) > 30) { 
    echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'&hellip;'; 
} 
0

在Laravel,有一個字符串util的這個功能,它是這樣實現:

public static function limit($value, $limit = 100, $end = '...') 
{ 
    if (mb_strwidth($value, 'UTF-8') <= $limit) { 
     return $value; 
    } 

    return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end; 
} 
0

$值= str_limit;(7 '這個字符串是真的很長。')

//這個ST ...