PHP 5.6.0 released

trim

(PHP 4, PHP 5)

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

説明

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

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

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

パラメータ

str

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

character_mask

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

返り値

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

例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 13 notes

up
15
ludko2 at gmail dot com
4 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
15
jubi at irc dot pl
10 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
3
Piopier
7 years ago
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
up
1
Hayley Watson
9 years ago
Another way to trim all the elements of an array
<?php
$newarray
= array_map('trim', $array);
?>
up
0
tbm.at.home.dot.nl
12 years ago
Windows uses two characters for definining newlines, namely ASCII 13 (carriage return, "\r") and ASCII 10 (line feed, "\n") aka CRLF. So if you have a string with CRLF's, trim() won't recognize them as being one newline. To solve this you can use str_replace() to replace the CRLF's with with a space or something.

<?php
// string with bunch of CRLF's
$my_string = "Liquid\r\nTension Experiment\r\n\r\n\r\n";

// replace CRLF's with spaces
$my_wonderful_string = str_replace("\r\n", " ", $my_string);
// would result in "Liquid Tension Experiment   "

// or just delete the CRLF's (by replacing them with nothing)
$my_wonderful_string = str_replace("\r\n", "", $my_string);
// would result in "LiquidTension Experiment"
?>
up
-1
josecruz at josecruz dot com dot br
5 years ago
A simple function to clear extra white spaces along a string.
<?php
function TrimStr($str)
{
   
$str = trim($str);
    for(
$i=0;$i < strlen($str);$i++)
    {

        if(
substr($str, $i, 1) != " ")
        {

           
$ret_str .= trim(substr($str, $i, 1));

        }
        else
        {
            while(
substr($str,$i,1) == " ")
          
            {
               
$i++;
            }
           
$ret_str.= " ";
           
$i--; // ***
       
}
    }
    return
$ret_str;
}
?>

[EDIT BY danbrown AT php DOT net: Contains a fix provided by (info AT deep-soft DOT com) to address the issue where "it deletes the first char after spaces (because of while)."]
up
-2
dmr37 at cornell dot edu
9 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
-1
tomdudman at gmail dot com
7 months ago
This function trims regular expressions from strings.

<?php
   
function preg_trim( $string, $pattern ) {
       
$pattern = array( "/^" . $pattern . "*/", "/" . $pattern . "*$/" );
        return
preg_replace( $pattern, "", $string );
    }
?>

The following example outputs "Hello, world":

<?php
    $hello
= "   ...%20Hello, world!";
    echo
preg_trim( $hello, "[^a-zA-Z]" );
?>
up
-4
seyednaser at gmail dot com
2 years ago
To show off the empty positions in a string by means of trim():

<?php
    $string
= "    Hello World!   ";
    echo
$string;
    echo
" Has : ".strlen($string)." letter(s). One by one according to the following:<br />";
    echo
"<br />".$rightt = strlen(ltrim($string)) - strlen(trim($string))." empty position(s) from right.";
    echo
"<br />".$leftt = strlen(rtrim($string)) - strlen(trim($string))." empty position(s) from left.<br />";
   
$length = strlen($string);
    for(
$x = 0; $x < $length; $x++){
   
$letter = substr($string, $x, 1);
        if(
$letter <> " ")
            echo
"<br />Position&nbsp;&nbsp; $x ===> &nbsp;&nbsp;".substr($string, $x, 1);
        else
            echo
"<br />Position&nbsp;&nbsp; $x ===> &nbsp;&nbsp; Empty";
    }   
?>

the output is:

Hello World! Has : 19 letter(s). One by one according to the following:

3 empty position(s) from right.
4 empty position(s) from left.

Position   0 ===>    Empty
Position   1 ===>    Empty
Position   2 ===>    Empty
Position   3 ===>    Empty
Position   4 ===>   H
Position   5 ===>   e
Position   6 ===>   l
Position   7 ===>   l
Position   8 ===>   o
Position   9 ===>    Empty
Position   10 ===>   W
Position   11 ===>   o
Position   12 ===>   r
Position   13 ===>   l
Position   14 ===>   d
Position   15 ===>   !
Position   16 ===>    Empty
Position   17 ===>    Empty
Position   18 ===>    Empty
up
-5
gerjoo at gmail dot com
3 years ago
On my application I had several users submit what to me appeared as "empty strings", whereas in fact they were submitting the &shy; character.

Trim, by default, does not strip this character (Though arguably it should). The following code strips this character from your input:

<?php

// As the &shy; character is invisible we'll simply use the ASCII numeric representation, and decode via chr():
$string = trim($string, chr(173));

// If you wish to strip all occurences this will work:
$string = str_replace(chr(173), "", $string);

?>

Gerard
up
-6
syn-attack at devilzc0de dot org
1 year ago
I think this is my implementation of trim...

<?php
   
/*
     * Function: "trim"
     * @str = source
     * @charlist = list of characters to be trimmed from the source
     *
     * Author: syn-attack@devilzc0de.org
     * Full documentation in http://php.net/manual/en/function.trim.php
     */
   
function __trim($str, $charlist = '') {
       
$result = '';
       
/* list of forbidden chars to be trimmed */
       
$forbidden_list = array(" ", "\t", "\r", "\n", "\0", "\x0B");
       
        if (empty(
$charlist)) {
            for (
$i = 0; $i < strlen($str); $i++) {
                if ((
$str[$i] != $forbidden_list[0]) &&
                    (
$str[$i] != $forbidden_list[1]) &&
                    (
$str[$i] != $forbidden_list[2]) &&
                    (
$str[$i] != $forbidden_list[3]) &&
                    (
$str[$i] != $forbidden_list[4]) &&
                    (
$str[$i] != $forbidden_list[5])) {
                   
$result .= $str[$i];
                }
            }
        }
        else if (!empty(
$charlist)) {
           
$is_not_same = true;
           
            for (
$i = 0; $i < strlen($str); $i++) {
                for (
$j = 0; $j < strlen($charlist); $j++) {
                    if (
$str[$i] != $charlist[$j]) {
                       
$is_not_same = true;
                    }
                    else if (
$str[$i] == $charlist[$j]) {
                       
$is_not_same = false;
                        break;
                    }
                }
               
                if (
$is_not_same == true) {
                   
$result .= $str[$i];
                }
            }
        }
       
        return (
$result);
    }
   
   
$str = "Paulus Gandung Prakosa";
    echo
__trim($str);
?>
up
-8
HW
11 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");
up
-4
Anonymous
6 months ago
if (preg_match('/[^\d]/', $pytanie_pomoc)) {
            throw new exception('special chars exists or spaces!.');
        }
To Top