trim

(PHP 4, PHP 5, PHP 7)

trim去除字符串首尾处的空白字符(或者其他字符)

说明

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

此函数返回字符串 str 去除首尾空白字符后的结果。如果不指定第二个参数,trim() 将去除这些字符:

  • " " (ASCII 32 (0x20)),普通空格符。
  • "\t" (ASCII 9 (0x09)),制表符。
  • "\n" (ASCII 10 (0x0A)),换行符。
  • "\r" (ASCII 13 (0x0D)),回车符。
  • "\0" (ASCII 0 (0x00)),空字节符。
  • "\x0B" (ASCII 11 (0x0B)),垂直制表符。

参数

str

待处理的字符串

character_mask

可选参数,过滤字符也可由 character_mask 参数指定。一般要列出所有希望过滤的字符,也可以使用 ".." 列出一个字符范围。

返回值

过滤后的字符串。

范例

Example #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);

// 清除 $binary 首位的 ASCII 控制字符
// (包括 0-31)
$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(14) "Example string"

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

注释

Note: Possible gotcha: removing middle characters

Because trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not.

参见

  • ltrim() - 删除字符串开头的空白字符(或其他字符)
  • rtrim() - 删除字符串末端的空白字符(或者其他字符)
  • str_replace() - 子字符串替换

User Contributed Notes

johovich at yandex dot ru 31-Jul-2017 07:17
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;
}
tongcheong77 at gmail dot com 09-Jul-2017 09:39
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.
ivijan dot stefan at gmail dot com 03-Jul-2017 06:06
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;
}
?>
Anonymous 12-Jun-2017 01:45
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à"`.
jianglong at qiyi dot com 13-May-2015 05:09
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").]
ludko2 at gmail dot com 09-Jul-2010 11:28
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!
?>
Piopier 12-Jan-2007 03:06
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
dmr37 at cornell dot edu 17-May-2005 09:47
If you want to check whether something ONLY has whitespaces, use the following:

<?php

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

?>
Hayley Watson 08-Feb-2005 01:46
Another way to trim all the elements of an array
<?php
$newarray
= array_map('trim', $array);
?>
jubi at irc dot pl 20-Apr-2004 03:48
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
HW 06-Jun-2003 03:32
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");