PHP 8.5.0 Alpha 1 available for testing

trim

(PHP 4, PHP 5, PHP 7, PHP 8)

trim Elimina los espacios (u otros caracteres) al inicio y al final de un string

Descripción

trim(string $string, string $characters = " \n\r\t\v\x00"): 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.

Parámetros

string

El string que será recortado.

characters
Opcionalmente, los caracteres a eliminar también pueden ser especificados utilizando el parámetro characters. Basta con listar todos los caracteres que deben ser eliminados. Con .., es posible especificar un rango creciente de caracteres.

Valores devueltos

El string recortado.

Ejemplos

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"
}

Notas

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 que trim('abc', 'b') no funciona.

Ver también

  • ltrim() - Elimina los espacios (u otros caracteres) del inicio de un string
  • rtrim() - Elimina los espacios (u otros caracteres) al final de un string
  • str_replace() - Reemplaza todas las ocurrencias en una string
add a note

User Contributed Notes 2 notes

up
14
pcoates at yukon1000 dot com
2 years ago
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']) : '';
up
2
gwyneth dot llewelyn at gwynethllewelyn dot net
2 years ago
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
To Top