Vers l'espace le plus proche
Tronque jusqu'à l'espace précédent le plus proche du caractère cible. Démo
-
$str
La chaîne de caractères à tronquer
-
$chars
Le nombre de caractères à supprimer peut être modifié par la fonction $to_space
-
$to_space
boolean
pour savoir s'il faut ou non tronquer de l'espace proche $chars
limite
Fonction
function truncateString($str, $chars, $to_space, $replacement="...") {
if($chars > strlen($str)) return $str;
$str = substr($str, 0, $chars);
$space_pos = strrpos($str, " ");
if($to_space && $space_pos >= 0)
$str = substr($str, 0, strrpos($str, " "));
return($str . $replacement);
}
Echantillon
<?php
$str = "this is a string that is just some text for you to test with";
print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");
?>
Sortie
this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--
1 votes
Vous pourriez trouver
s($str)->words(20)
utile, comme on le trouve dans cette bibliothèque autonome .