2010-06-10 16 views
38

Sto cercando un modo per limitare una stringa in php e aggiungere ... alla fine se la stringa era troppo lunga.Lunghezza stringa limite

+0

si potrebbe trovare [ 's ($ str) -> truncate ($ lunghezza)'] (https://github.com/delight-im/PHP-Str/ blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php # L233) o anche ['s ($ str) -> truncateSafely ($ length)'] (https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc /src/Str.php#L246) utile, come trovato in [questa libreria standalone] (https://github.com/delight-im/PHP-Str). – caw

risposta

90

Si può usare qualcosa di simile al di sotto:

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

Immagino che non pensassi che potrebbe saltare i suoi compiti di lettura. – dlamblin

+0

Scusate, non l'ho considerato. Quali sono le regole per i compiti? Oh e aspetta, ho appena notato, il mio codice non funziona nemmeno correttamente;) – bramp

+2

È solo una regola di community: http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer -homework-questions – dlamblin

0

troncare una stringa fornito dal limite massimo senza rompere la parola usa questo:

/** 
* 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

da php 4.0.6 , C'è una funzione per la stessa identica cosa

funzione mb _ strimwidth può essere utilizzato per il vostro requisito

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

Essa ha ancora più opzioni, però, qui è la documentazione per questo mb_strimwidth

+0

La funzione wordwrap() può anche essere utile: http://www.w3schools.com/php/func_string_wordwrap.asp –

+0

Ma personalmente, preferisco usare: $ s = preg_replace ('/ \ s +? (\ S +)? $/',' ', substr ($ s, $ START, $ LIMIT)); –

+2

@CyrilJacquart è meglio evitare l'uso di espressioni regolari dove mai non è necessario. –

0

In un altro modo per limitare una stringa in php e aggiungere testo readmore o come '...' utilizzando il codice sottostante

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

In laravel, v'è una stringa util della funzione di questo, ed è implementato in questo modo:

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

$ value = str_limit; (, 7 'Questa stringa è molto molto lungo.')

// Questa st ...

Problemi correlati