腾讯云618限量抢购
  1. PHP+MySQL数据库教程
  2. PHP进阶教程
  3. ThinkPHP 3.0/3.1 教程

PHP 字符串去除 trim、ltrim 与 rtrim 函数

最后更新:2010-10-19 17:05阅读:47530

PHP 字符串去除

用于去除字符串首尾空白等特殊符号或指定的字符。

相关函数如下:

  • trim():去除字符串 首尾 空白等特殊符号或指定字符序列
  • ltrim():去除字符串 首 空白等特殊符号或指定字符序列
  • rtrim():去除字符串 尾 空白等特殊符号或指定字符序列
  • chop():同rtrim()

trim()

去除字符串首尾空白等特殊符号或指定字符序列。

语法:

string trim(string str[, charlist])

当设定字符序列 charlist 参数时,trim() 函数将去除字符串首尾的这些字符,否则 trim() 函数将去除字符串首尾的以下这些特殊字符:

字符 说明
空格
t tab键
n 换行符
r a carriage return
空字符
x0B a vertical tab

例子:

<?php
$text = "Hello World ";
$trimmed = trim($text);
echo $trimmed;			//输出"Hello World"
echo "<br />";
echo trim($trimmed, "Hdle"); 	//输出"o Wor"
echo "<br />";
echo trim($text, "Hdle");	//输出"o World"
?>

从这个例子可以看出,trim() 函数将不会去除非首尾的 charlist 。

ltrim()

去除字符串首的特殊符号或指定字符序列,用法同 trim() 。

语法:

string ltrim(string str[, charlist])

rtrim()

去除字符串尾的特殊符号或指定字符序列,用法同 trim() 。

语法:

string rrim(string str[, charlist])

chop()

同 rtrim() 。


本章节内容共分 10 部分:
  1. 1. PHP 字符串输出 echo、print 与 printf 函数
  2. 2. PHP 字符串去除 trim、ltrim 与 rtrim 函数
  3. 3. PHP implode 函数:将数组元素组合为字符串
  4. 4. PHP 字符串获取 substr 与 strstr 函数
  5. 5. PHP 字符串计算 strlen、strpos 与 strrpos 函数
  6. 6. PHP 字符串 XHTML格式化显示 nl2br 与 htmlspecialchars 函数
  7. 7. PHP 字符串存储(转义) addslashes 与 stripslashes 函数
  8. 8. PHP 字符串分割 explode 与 str_split 函数
  9. 9. PHP 字符串替换 substr_replace 与 str_replace 函数
  10. 10. PHP 字符串处理
腾讯云618限量抢购