(PHP 4, PHP 5, PHP 7, PHP 8)
trim — Elimina los espacios (u otros caracteres) al inicio y al final de un string
trim() retorna el string string, después
de haber eliminado los caracteres invisibles al inicio y al final del string.
Si el segundo parámetro characters es omitido,
trim() eliminará los siguientes caracteres:
" ": carácter SP en ASCII
0x20, un espacio ordinario.
"\t": carácter HT en ASCII
0x09, una tabulación.
"\n": carácter LF en ASCII
0x0A, un salto de línea (line feed).
"\r": carácter CR en ASCII
0x0D, un retorno de carro.
"0円": carácter NUL en ASCII
0x00, el octeto NUL.
"\v": carácter VT en ASCII
0x0B, una tabulación vertical.
stringEl string que será recortado.
characterscharacters.
Basta con listar todos los caracteres que deben ser eliminados.
Con .., es posible especificar un rango creciente de caracteres.
El string recortado.
Ejemplo #1 Ejemplo con 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);
$trimmed = trim($hello, 'HdWr');
var_dump($trimmed);
// Elimina los caracteres de control ASCII al inicio y al final de $binary
// (de 0 a 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
?>El ejemplo anterior mostrará:
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(9) "ello Worl" string(14) "Example string"
Ejemplo #2 Eliminación de caracteres en un array con 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);
?>El ejemplo anterior mostrará:
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"
}
Nota: Posible uso: eliminación de caracteres en medio del string
Debido a que la función trim() elimina caracteres al inicio y al final del string, puede resultar confuso cuando los caracteres son (o no) eliminados desde el medio.
trim('abc', 'bad')elimina tanto 'a' como 'b' porque la función elimina 'a', luego, mueve 'b' al inicio del string, que también será eliminado. Asimismo, es la razón por la cual la función "funciona" mientras quetrim('abc', 'b')no funciona.
note there is a behaviour change in php 8
You used to be able to say:
$p1 = trim($_POST['p1']);
This will now throw deprecated warnings if parameter p1 is not set. It is better to say:
$p1 = trim($_POST['p1']??'');
or
$p1 = isset($_POST['p1']) ? trim($_POST['p1']) : null;
or
$p1 = isset($_POST['p1']) ? trim($_POST['p1']) : '';Note that trim() is not aware of Unicode points that represent whitespace (e.g., in the General Punctuation block), except, of course, for the ones mentioned in this page.
There is no Unicode-specific trim function in PHP at the time of writing (July 2023), but you can try some examples of trims using multibyte strings posted on the comments for the mbstring extension: https://www.php.net/manual/en/ref.mbstring.php