2008-11-25 8 views
57

Je cherche un moyen de tirer les 100 premiers caractères d'une variable de chaîne pour mettre dans une autre variable pour l'impression.Comment tirer les 100 premiers caractères d'une chaîne en PHP

Y at-il une fonction qui peut le faire facilement?

Par exemple:

$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing."; 
$string2 = 100charfunction($string1); 
print $string2 

Pour obtenir:

I am looking for a way to pull the first 100 characters from a string vari 

Répondre

143
$small = substr($big, 0, 100); 

Pour String Manipulation ici est une page avec beaucoup de fonctions qui pourraient vous aider dans votre travail futur.

+1

il y a un problème sur le retour du texte arabe, car ils sont des mots avec des lettres combinées si le second paramètre (100) ne sont pas à la fin des mots arabes sur le dernier tout en comptant 100, il renvoie null . pour cela, nous allons utiliser (mb_substr ($ big, 0,100) – SAR

18

essayer cette fonction

function summary($str, $limit=100, $strip = false) { 
    $str = ($strip == true)?strip_tags($str):$str; 
    if (strlen ($str) > $limit) { 
     $str = substr ($str, 0, $limit - 3); 
     return (substr ($str, 0, strrpos ($str, ' ')).'...'); 
    } 
    return trim($str); 
} 
27

Vous pouvez utiliser substr, je suppose:

$string2 = substr($string1, 0, 100); 

ou mb_substr pour les chaînes multi-octets:

$string2 = mb_substr($string1, 0, 100); 

Vous pouvez créer une fonction Wich utilise cette fonction et ajoute par exemple '...' pour indiquer qu'il a été raccourci. (Je suppose qu'il ya une centaine de réponses allready semblables lorsque cela est affiché ...)

19
$x = '1234567'; 

echo substr ($x, 0, 3); // outputs 123 

echo substr ($x, 1, 1); // outputs 2 

echo substr ($x, -2); // outputs 67 

echo substr ($x, 1);  // outputs 234567 

echo substr ($x, -2, 1); // outputs 6 
+1

Merci, cela résume joliment les variables de la fonction substr() – JoshFinnie

2

Sans fonctions internes php:

function charFunction($myStr, $limit=100) {  
    $result = ""; 
    for ($i=0; $i<$limit; $i++) { 
     $result .= $myStr[$i]; 
    } 
    return $result;  
} 

$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing."; 

echo charFunction($string1); 
13

Une réponse tardive, mais utile, PHP a une fonction spécifique pour cette objectif.

mb_strimwidth

$string = mb_strimwidth($string, 0, 100); 
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end 
+1

Bon 1 ... Vraiment utile. – RJParikh

Questions connexes