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)),NUL字节。
- “\ x0B”(ASCII 11(0x0B)),一个垂直标签。
参数
str
将被修剪的字符串。
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);
//?trim?the?ASCII?control?characters?at?the?beginning?and?end?of?$binary
//?(from?0?to?31?inclusive)
$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()从字符串的开头和结尾修剪字符,当字符从中间移除(或不)时可能会引起混淆。trim('abc','bad')会删除'a'和'b',因为它会修剪'a',因此会将'b'移动到开头并进行修剪。所以,这就是为什么它“起作用”,而trim('abc','b')看起来不是。
扩展内容
- ltrim() - 从字符串的开头去除空格(或其他字符)
- rtrim() - 从字符串的末尾去除空格(或其他字符)
- str_replace() - 用替换字符串替换所有出现的搜索字符串
← substr
ucfirst →
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com