PHP trim() 函数
PHP 教程
· 2019-01-30 14:28:33
实例
移除字符串左侧的字符("Hello" 中的 "He"以及 "World" 中的 "d!"):
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
定义和用法
trim() 函数移除字符串两侧的空白字符或其他预定义字符。
相关函数:
- ltrim() - 移除字符串左侧的空白字符或其他预定义字符。
- rtrim() - 移除字符串右侧的空白字符或其他预定义字符。
语法
trim(string,charlist)
| 参数 | 描述 |
|---|---|
| string | 必需。规定要检查的字符串。 |
| charlist | 可选。规定从字符串中删除哪些字符。如果省略该参数,则移除下列所有字符:
|
技术细节
| 返回值: | 返回已修改的字符串。 |
|---|---|
| PHP 版本: | 4+ |
| 更新日志: | 在 PHP 4.1 中,新增了 charlist 参数。 |
更多实例
实例 1
移除字符串两侧的空格:
<?php
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>
$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>
<html>
<body>
Without trim: Hello World! <br>With trim: Hello World!
</body>
</html>
上面代码的浏览器输出如下:
Without trim: Hello World!
With 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);
?>
$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>
<html>
<body>
Without trim:
Hello World!
<br>With trim: Hello World!
</body>
</html>
上面代码的浏览器输出如下:
Without trim: Hello World!
With trim: Hello World!
With trim: Hello World!
点击查看所有 PHP 教程 文章: https://codercto.com/courses/l/5.html
我的第一本算法书
[日]石田保辉、[日]宮崎修一 / 张贝 / 人民邮电出版社 / 2018-10 / 69.00元
本书采用大量图片,通过详细的分步讲解,以直观、易懂的方式展现了7个数据结构和26个基础算法的基本原理。第1章介绍了链表、数组、栈等7个数据结构;从第2章到第7章,分别介绍了和排序、查找、图论、安全、聚类等相关的26个基础算法,内容涉及冒泡排序、二分查找、广度优先搜索、哈希函数、迪菲 - 赫尔曼密钥交换、k-means 算法等。 本书没有枯燥的理论和复杂的公式,而是通过大量的步骤图帮助读者加深......一起来看看 《我的第一本算法书》 这本书的介绍吧!