PHP 7.2.0 Alpha 2 Released

trim

(PHP 4, PHP 5, PHP 7)

trimRetira espaço no ínicio e final de uma string

Descrição

string trim ( string $str [, string $charlist ] )

Esta função retorna uma string com os espaçoes retirados do ínicio e do final de str. Sem o segundo parâmetro, trim() irá retirar estes caracteres

  • " " (ASCII 32 (0x20)), um espaço normal.
  • "\t" (ASCII 9 (0x09)), uma tabulação.
  • "\n" (ASCII 10 (0x0A)), uma linha nova (line feed).
  • "\r" (ASCII 13 (0x0D)), um retono de carro.
  • "\0" (ASCII 0 (0x00)), o byte NULL.
  • "\x0B" (ASCII 11 (0x0B)), uma tabulação vertical.

Parâmetros

str

A string que será modificada.

charlist

Opcionalmente, os caracteres removidos pode também ser especificados usando o parâmetro charlist. Simplesmente liste todos os caracteres que você quer retirar. Com .. você pode especificar um intervalo de caracteres.

Valor Retornado

A string com caracteres removidos.

Changelog

Versão Descrição
4.1.0 O parâmetro opcional charlist foi adicionado.

Exemplos

Exemplo #1 Exemplo 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);

// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean trim($binary"\x00..\x1F");
var_dump($clean);

?>

O exemplo acima irá imprimir:

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"

Exemplo #2 Usando trim() em valores de 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);

?>

O exemplo acima irá imprimir:

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

Veja Também

  • ltrim() - Retira espaços em branco (ou outros caracteres) do início da string
  • rtrim() - Retira espaço em branco (ou outros caracteres) do final da string

add a note add a note

User Contributed Notes 8 notes

up
49
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
39
ludko2 at gmail dot com
6 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
19
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
8
Hayley Watson
12 years ago
Another way to trim all the elements of an array
<?php
$newarray
= array_map('trim', $array);
?>
up
0
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
Anonymous
11 days 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
-15
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
-26
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