(PHP 4, PHP 5, PHP 7)
trim — 去锟斤拷锟街凤拷锟斤拷锟斤拷尾锟斤拷锟侥空帮拷锟街凤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟街凤拷锟斤拷
$str
[, string $character_mask
= " \t\n\r\0\x0B"
] ) : string
锟剿猴拷锟斤拷锟斤拷锟斤拷锟街凤拷锟斤拷 str
去锟斤拷锟斤拷尾锟秸帮拷锟街凤拷锟斤拷慕锟斤拷锟斤拷锟斤拷锟斤拷锟街革拷锟斤拷诙锟斤拷锟斤拷锟斤拷锟斤拷锟�trim() 锟斤拷去锟斤拷锟斤拷些锟街凤拷锟斤拷
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.