实例
移除字符串左侧的字符(hello 中的 he以及 world 中的 d!):
<?php
$str = "hello world!";
echo $str . "<br>";
echo trim($str,"hed!");
?>
定义和用法
trim() 函数移除字符串两侧的空白字符或其他预定义字符。
相关函数:
ltrim() - 移除字符串左侧的空白字符或其他预定义字符。
rtrim() - 移除字符串右侧的空白字符或其他预定义字符。
语法
trim(string,charlist)
参数 描述
string 必需。规定要检查的字符串。
charlist 可选。规定从字符串中删除哪些字符。如果省略该参数,则移除下列所有字符:"\0" - null
"\t" - 制表符
"\n" - 换行
"\x0b" - 垂直制表符
"\r" - 回车
" " - 空格
技术细节
返回值: 返回已修改的字符串。
php 版本: 4+
更新日志: 在 php 4.1 中,新增了 charlist 参数。
更多实例
实例 1
移除字符串两侧的空格:
<?php
$str = " hello world! ";
echo "without trim: " . $str;
echo "<br>";
echo "with trim: " . trim($str);
?>
上面代码的 html 输出如下(查看源代码):
<!doctype html>
<html>
<body>
without trim: hello world! <br>with trim: hello world!
</body>
</html>
上面代码的浏览器输出如下:
without trim: hello world!
with trim: hello world!
实例 2
移除字符串两侧的换行符(\n):
<?php
$str = "nnnhello world!nnn";
echo "without trim: " . $str;
echo "<br>";
echo "with trim: " . trim($str);
?>
上面代码的 html 输出如下(查看源代码):
<!doctype html>
<html>
<body>
without trim:
hello world!
<br>with trim: hello world!
</body>
</html>
上面代码的浏览器输出如下:
without trim: hello world!
with trim: hello world!
例子
<?php
$str = "##使用函数trim去掉字符串两端特定字符####";
$str1 = trim($str,"#");
//为函数trim传入第二个参数,
trim将删除字符串$str两端的#字符 echo $str."<br>";
echo $str1;
?>
输出:
##使用php函数trim()去掉字符串两端特定字符#### 使用函数trim去掉字符串两端特定字符
以上就是php移除字符串两侧的空白字符或其他预定义字符的函数trim()的详细内容。