Dernière mise à jour: ven 29 jan 2010

truncate()

(PHP 4, PHP 5)

Tronque une chaine à une certaine longueur.

truncate() retourne la chaîne string tronquée d'une longueur maximale de max_length caractères.

Source

<?php

function truncate($string, $max_length = 30, $replacement = '', $trunc_at_space = false)
{
	$max_length -= strlen($replacement);
	$string_length = strlen($string);
	
	if($string_length <= $max_length)
		return $string;
	
	if( $trunc_at_space && ($space_position = strrpos($string, ' ', $max_length-$string_length)) )
		$max_length = $space_position;
	
	return substr_replace($string, $replacement, $max_length);
}

?>

Syntaxe

string truncate ( string $string [, integer $max_length = 30 [, string $replacement = '' [, bool $trunc_at_space = false ]]] )

Arguments

  1. string - La chaîne d'entrée.
  2. max_length - Longueur maximale de la chaine retournée.
  3. replacement - Texte de remplacement.
  4. trunc_at_space - Si ce paramètre vaut TRUE, truncate() tentera de ne pas tronquer la chaine au milieu d'un mot.

Valeurs de retour

Retourne la chaîne tronquée.

Exemples

Exemple #1 Exemple avec truncate()

<?php

$str = "Suspendisse at magna non lectus lacinia gravida.";
$str = truncate($str);
echo $str; // Suspendisse at magna non lectu

?>

Exemple #2 Exemple avec truncate()

<?php

$str = "Suspendisse at magna non lectus lacinia gravida.";
$str = truncate($str, 40, '...', true);
echo $str; // Suspendisse at magna non lectus...

?>

Voir aussi

Commentaire(s)

Il n'y a aucun commentaire pour cette page.

Poster un commentaire