字符串函数
PHP 手册

trim

(PHP 4, PHP 5)

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

说明

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

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

参数

str

待处理的字符串

charlist

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

返回值

过滤后的字符串。

更新日志

版本 说明
4.1.0 新增可选的 charlist 参数。

范例

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.

参见


字符串函数
PHP 手册