(PHP 4, PHP 5)
trim — Supprime les espaces (ou d'autres caractères) en début et fin de chaîne
trim() retourne la chaîne str, après avoir supprimé les caractères invisibles en début et fin de chaîne. Si le second paramètre charlist est omis, trim() supprimera les caractères suivants :
La chaîne de caractères qui sera coupé.
Optionnellement, les caractères supprimés peuvent aussi être spécifiés en utilisant le paramètre charlist. Listez simplement tous les caractères que vous voulez supprimer. Avec .. vous pouvez spécifier une plage de caractères.
La chaîne de caractères coupée.
Version | Description |
---|---|
4.1.0 | Le paramètre optionnel charlist a été ajouté. |
Exemple #1 Exemple avec trim()
<?php
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "\n";
$trimmed = trim($text);
var_dump($trimmed);
$trimmed = trim($text, " \t.");
var_dump($trimmed);
$trimmed = trim($hello, "Hdle");
var_dump($trimmed);
// Supprime les caractères de contrôle ASCII au début et à la fin de $binary
// (de 0 à 31 inclusif)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
?>
L'exemple ci-dessus va afficher :
string(32) " These are a few words :) ... " string(16) " Example string " string(11) "Hello World" string(28) "These are a few words :) ..." string(24) "These are a few words :)" string(5) "o Wor" string(14) "Example string"
Exemple #2 Suppression de caractères dans un tableau avec trim()
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
L'exemple ci-dessus va afficher :
array(3) { [0]=> string(5) "apple" [1]=> string(7) "banana " [2]=> string(11) " cranberry " } array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(9) "cranberry" }