trim

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

trim 文字列の先頭および末尾にあるホワイトスペースを取り除く

説明

trim(string $string, string $characters = " \n\r\t\v\x00"): string

この関数は string の最初および最後から空白文字を取り除き、 取り除かれた文字列を返します。2番目のパラメータを指定しない場合、 trim()は以下の文字を削除します。

  • " " (ASCII 32 (0x20)), 通常の空白。
  • "\t" (ASCII 9 (0x09)), タブ。
  • "\n" (ASCII 10 (0x0A)), リターン。
  • "\r" (ASCII 13 (0x0D)), 改行。
  • "\0" (ASCII 0 (0x00)), NULバイト
  • "\v" (ASCII 11 (0x0B)), 垂直タブ

パラメータ

string

ホワイトスペースを取り除く string

characters

charactersパラメータにより、削除する 文字を指定することも可能です。削除したい全ての文字をリストに してください。..を文字の範囲を指定する際に 使用可能です。

戻り値

ホワイトスペースを取り除いた文字列

例1 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);

// ASCII 制御文字 (0 から 31 まで) を
// $binary の先頭および末尾から取り除きます
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?>

上の例の出力は以下となります。

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"

例2 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);

?>

上の例の出力は以下となります。

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

注意

注意: わかるかな?: 途中の文字が取り除かれる

trim()string の先頭と末尾から文字を取り除くので、 文字列の途中にある文字がを取り除かれたり (あるいは取り除かれなかったり) すると少し戸惑うことでしょう。 trim('abc', 'bad') は 'a' と 'b' を両方取り除きます。 なぜなら、まず 'a' を取り除いた時点で 'b' が先頭の文字となり、それも取り除く対象だからです。 したがって、この処理は正しく動きます。一方、 trim('abc', 'b') は動かないでしょう。

参考

  • ltrim() - 文字列の最初から空白 (もしくはその他の文字) を取り除く
  • rtrim() - 文字列の最後から空白 (もしくはその他の文字) を取り除く
  • str_replace() - 検索文字列に一致したすべての文字列を置換する

add a note add a note

User Contributed Notes 18 notes

up
170
Piopier
17 years ago
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
up
57
ludko2 at gmail dot com
13 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
21
aalhad at NOSPAM dot gmail dot com
6 years ago
When specifying the character mask,
make sure that you use double quotes

<?php
  $hello
= "
      Hello World   "
; //here is a string with some trailing and leading whitespace

 
$trimmed_correct   = trim($hello, " \t\n\r"); //<--------OKAY
 
$trimmed_incorrect = trim($hello, ' \t\n\r'); //<--------NOT AS EXPECTED

 
print("----------------------------");
  print(
"TRIMMED OK:".PHP_EOL);
 
print_r($trimmed_correct.PHP_EOL);
  print(
"----------------------------");
  print(
"TRIMMING NOT OK:".PHP_EOL);
 
print_r($trimmed_incorrect.PHP_EOL);
  print(
"----------------------------".PHP_EOL);
?>

Here is the output:

----------------------------TRIMMED OK:
Hello World
----------------------------TRIMMING NOT OK:

      Hello World
----------------------------
up
1
a at b dot com
2 years ago
Care should be taken if the string to be trimmed contains intended characters from the definition list.

E.g. if you want to trim just starting and ending quote characters, trim will also remove a trailing quote that was intentionally contained in the string, if at position 0 or at the end, and if the string was defined in double quotes, then trim will only remove the quote character itself, but not the backslash that was used for it's definition. Yields interesting output and may be puzzling to debug...
up
6
roger21 at free dot fr
4 years ago
It is worth mentioning that trim, ltrim and rtrim are NOT multi-byte safe, meaning that trying to remove an utf-8 encoded non-breaking space for instance will result in the destruction of utf-8 characters than contain parts of the utf-8 encoded non-breaking space, for instance:

non breaking-space is "\u{a0}" or "\xc2\xa0" in utf-8, "µ" is "\u{b5}" or "\xc2\xb5" in utf-8 and "à" is "\u{e0}" or "\xc3\xa0" in utf-8

$input = "\u{a0}µ déjà\u{a0}"; // " µ déjà "
$output = trim($input, "\u{a0}"); // "▒ déj▒" or whatever how the interpretation of broken utf-8 characters is performed

$output got both "\u{a0}" characters removed but also both "µ" and "à" characters destroyed
up
22
jubi at irc dot pl
19 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
5
johovich at yandex dot ru
6 years 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
10
Hayley Watson
19 years ago
Another way to trim all the elements of an array
<?php
$newarray
= array_map('trim', $array);
?>
up
2
jianglong at qiyi dot com
8 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
0
mihow
2 years ago
This is the best solution I've found that strips all types of whitespace and it multibyte safe

$new_str = trim(preg_replace("/\s+/u", " ", $str));

Solution taken from here:
https://stackoverflow.com/a/40264711/966058
up
0
tongcheong77 at gmail dot com
6 years 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
0
Anonymous
6 years 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
-3
ivijan dot stefan at gmail dot com
6 years 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
Mark-Centurion at ya dot ru
5 years ago
utf-8:
trim($text, " \t\n\r\0\x0B\xC2\xA0");
up
-34
dmr37 at cornell dot edu
18 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
-10
solaimanshah059 at gmail dot com
5 years ago
Simple Example I hope you will understand easily:

<?php

// Inserting empty variable;

$name = "";

if( !(empty(
$name )) )
{
  
$sql = "INSERT INTO `users`( name ) VALUE( '$name' );";
}

// But is not empty that will be inserted but space

$name2 = "     ";

if( !(empty(
$name )) )
{
  
$sql = "INSERT INTO `users`( name ) VALUE( '$name' );";
}

// Now that will not be inserted by using trim() function

$name3 = "     ";

if( !(empty(
trim($name) )) )
{
  
$sql = "INSERT INTO `users`( name ) VALUE( '$name' );";
}

?>
up
-4
igor dot pellegrini at berlinonline dot de
4 years ago
Beware with trimming apparently innocent characters. It is NOT a Unicode-safe function:

<?php
echo trim('≈ [Approximation sign]', '– [en-dash]');  // �� [Approximation sig
?>

The en-dash here is breaking the Unicode characters.

And also prevents the open-square-bracket from being seen as part of the characters to trim on the left side, letting it untouched in the resulting string.
up
-52
HW
20 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