PHP 7.1.12 Released

trim

(PHP 4, PHP 5, PHP 7)

trimElimina espacio en blanco (u otro tipo de caracteres) del inicio y el final de la cadena

Descripción

string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] )

Esta función devuelve una cadena con los espacios en blanco eliminados del inicio y final del str. sin el segundo parámetro, trim() eliminará estos caracteres:

  • " " (ASCII 32 (0x20)), espacio simple.
  • "\t" (ASCII 9 (0x09)), tabulación.
  • "\n" (ASCII 10 (0x0A)), salto de línea.
  • "\r" (ASCII 13 (0x0D)), retorno de carro.
  • "\0" (ASCII 0 (0x00)), el byte NUL.
  • "\x0B" (ASCII 11 (0x0B)), tabulación vertical.

Parámetros

str

La cadena que será recortada.

character_mask

De manera opcional, los caracteres a ser eliminados pueden ser especificados usando el parámetro character_mask. Simplemente lista todos los caracteres que se quieran eliminar. Se puede especificar un rango de caracteres usando ...

Valores devueltos

La cadena recortada.

Ejemplos

Ejemplo #1 Ejemplo de uso de 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 final de $binary
// (from 0 to 31 inclusive)
$clean trim($binary"\x00..\x1F");
var_dump($clean);

?>

El resultado del ejemplo sería:

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 Uso de trim() en valores de un array

<?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 resultado del ejemplo sería:

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 trampa: eliminando caracteres de en medio

Debido a que trim() recorta los caracteres del principio y el final de un string, puede ser confuso cuando caracteres son (o no son) removidos del medio. trim('abc', 'bad') remueve tanto 'a' como 'b' debido a que cuando recorta 'a' entonces 'b' se mueve al inicio para también ser recortado. Por lo tanto, es por eso que "funciona", mientras que en trim('abc', 'b'), aparentemente no es así.

Ver también

  • ltrim() - Retira espacios en blanco (u otros caracteres) del inicio de un string
  • rtrim() - Retira los espacios en blanco (u otros caracteres) del final de un string
  • str_replace() - Reemplaza todas las apariciones del string buscado con el string de reemplazo

add a note add a note

User Contributed Notes 11 notes

up
54
Piopier
10 years ago
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
up
41
ludko2 at gmail dot com
7 years ago
Non-breaking spaces can be troublesome with trim:

<?php
// turn some HTML with non-breaking spaces into a "normal" string
$myHTML = "&nbsp;abc";
$converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));

// this WILL NOT work as expected
// $converted will still appear as " abc" in view source
// (but not in od -x)
$converted = trim($converted);

// &nbsp; are translated to 0xA0, so use:
$converted = trim($converted, "\xA0"); // <- THIS DOES NOT WORK

// EDITED>>
// UTF encodes it as chr(0xC2).chr(0xA0)
$converted = trim($converted,chr(0xC2).chr(0xA0)); // should work

// PS: Thanks to John for saving my sanity!
?>
up
20
jubi at irc dot pl
13 years ago
To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

<?

$text = preg_replace('/\s+/', ' ', $text);

?>

------------
JUBI
http://www.jubi.buum.pl
up
9
Hayley Watson
12 years ago
Another way to trim all the elements of an array
<?php
$newarray
= array_map('trim', $array);
?>
up
0
tongcheong77 at gmail dot com
4 months ago
if you are using trim and you still can't remove the whitespace then check if your closing tag inside the html document is NOT at the next line.

<textarea class="form-control" rows="5"><?php echo trim($comment);?></textarea>

there should be no spaces at the beginning and end of your echo statement, else trim will not work as expected.
up
-1
jianglong at qiyi dot com
2 years ago
Trim full width space will return mess character,  when target string starts with '《'

@example 
echo trim("《", " ");

@return


php version 5.4.27

[EDIT by cmb AT php DOT net: it is not necessarily safe to use trim with multibyte character encodings. The given example is equivalent to echo trim("\xe3\80\8a", "\xe3\x80\x80").]
up
-1
ivijan dot stefan at gmail dot com
4 months ago
Standard trim() functions can be a problematic when come HTML entities. That's why i wrote "Super Trim" function what is used to handle with this problem and also you can choose is trimming from the begin, end or booth side of string.
<?php
function strim($str,$charlist=" ",$option=0){
    if(
is_string($str))
    {
       
// Translate HTML entities
       
$return = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
       
// Remove multi whitespace
       
$return = preg_replace("@\s+\s@Ui"," ",$return);
       
// Choose trim option
       
switch($option)
        {
           
// Strip whitespace (and other characters) from the begin and end of string
           
default:
            case
0:
               
$return = trim($return,$charlist);
            break;
           
// Strip whitespace (and other characters) from the begin of string
           
case 1:
               
$return = ltrim($return,$charlist);
            break;
           
// Strip whitespace (and other characters) from the end of string
           
case 2:
               
$return = rtrim($return,$charlist);
            break;
               
        }
    }
    return
$return;
}
?>
up
-1
Anonymous
5 months ago
The comment of "ludko2 at gmail dot com" for trimming non-breaking spaces is wrong due the the way UTF-8 works. For example, it breaks on `"&nbsp;abà"`.
up
-1
johovich at yandex dot ru
3 months ago
trim is the fastest way to remove first and last char.

Benchmark comparsion 4 different ways to trim string with  '/'
4 functions with the same result - array exploded by '/'

<?php
$s
= '/catalog/lyustry/svet/dom-i-svet/';

$times = 100000;

print
cycle("str_preg('$s');", $times);
print
cycle("str_preg2('$s');", $times);
print
cycle("str_sub_replace('$s');", $times);
print
cycle("str_trim('$s');", $times);
print
cycle("str_clear('$s');", $times);

//print_r(str_preg2($s));

function cycle($function, $times){
   
$count = 0;
    if(
$times < 1){
        return
false;
    }
   
$start = microtime(true);
    while(
$times > $count){
        eval(
$function);
       
$count++;
    }
   
$end = microtime(true) - $start;
    return
"\n $function exec time: $end";
}

function
str_clear($s){
   
$s = explode('/', $s);
   
$s = array_filter($s, function ($s){if(!empty($s)) return true;});
    return
$s;
}

function
str_preg2($s){
   
$s = preg_replace('/((?<!.)\/(?=.))?((?<=.)\/(?!.))?/i', '', $s);
   
$s = explode('/', $s);
    return
$s;
}

function
str_preg($s){
   
$s = preg_replace('/^(\/?)(.*?)(\/?)$/i', '$2', $s);
   
$s = explode('/', $s);
    return
$s;
}

function
str_sub_replace($s){
   
$s = str_replace('/' , '' , mb_substr( $s , 0, 1)) . mb_substr( $s , 1, -1) . str_replace('/', '', mb_substr$s , -1));
   
$s = explode('/', $s);
    return
$s;
}

function
str_trim($s){
   
$s = trim($s, '/');
   
$s = explode('/', $s);
    return
$s;
}
up
-16
dmr37 at cornell dot edu
12 years ago
If you want to check whether something ONLY has whitespaces, use the following:

<?php

if (trim($foobar)=='') {
   echo
'The string $foobar only contains whitespace!';
}

?>
up
-29
HW
14 years ago
You can combine character ranges and individual characters in trim()'s second argument (ditto for ltrim and rtrim). All of the specified characters and ranges will be used concurrently (i.e., if a character on either end of the string matches any of the specified charaters or character ranges, it will be trimmed). The characters and character ranges can be in any order (except of course that the character ranges need to be specified in increasing order) and may overlap.
E.g., trim any nongraphical non-ASCII character:
trim($text,"\x7f..\xff\x0..\x1f");
To Top