ltrim、rtrim与trim 去除空格或者别的字符

ltrim、rtrim与 trim 函数
返回 Variant (String),其中包含指定字符串的拷贝,没有前导空白 (ltrim)、尾随空白 (rtrim) 或前导和尾随空白 (trim)。语法ltrim(string)rtrim(string)trim(string)必要的 string 参数可以是任何有效的字符串表达式。
如果 string 包含 Null,将返回 Null。
   
ltrim、rtrim 和 trim 函数的区别   
返回不带前导空格 (ltrim)、后续空格 (rtrim) 或前导与后续空格 (trim) 的字符串副本。  
 ltrim(string)   rtrim(string)   trim(string)   
string 参数是任意有效的字符串表达式。如果 string 参数中包含 Null,则返回 Null。   

 下面的示例利用 ltrim, rtrim, 和 trim 函数分别用来除去字符串开始的空格、尾部空格、 开始和尾部空格:   

 $MyVar = ltrim(" vbscript ") //$MyVar 包含 "vbscript "。
$MyVar = rtrim(" vbscript ") //$MyVar 包含 " vbscript"
$MyVar = trim(" vbscript ") //$MyVar 包含 "vbscript"

===========

string trim ( string $str [, string $charlist ] )
//去除首尾空白字符
string ltrim ( string $str [, string $charlist ] )
//去除左边空白字符
string rtrim ( string $str [, string $charlist ] )
//去除右边空白字符

这些函数返回字符串 str 去除空白字符后的结果。如果不指定第二个参数,3个函数将去除这些字符:

" " (ASCII 32 (0x20)),普通空格符。
"\t" (ASCII 9 (0x09)),制表符。
"\n" (ASCII 10 (0x0A)),换行符。
"\r" (ASCII 13 (0x0D)),回车符。
"\0" (ASCII 0 (0x00)),空字节符。
"\x0B" (ASCII 11 (0x0B)),垂直制表符。

通过指定 charlist,可以指定想要删除的字符列表。简单地列出你想要删除的全部字符。使用 .. 格式,可以指定一个范围。

$text   "\t\tThese are a few words :) ...  ";
$binary "\x09Example string\x0A";

//\x09是\t,\xoA是\n
$hello  "Hello World";
var_dump($text$binary$hello);

输出:

tring(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

--------------------------

trim的用法:

$trimmed trim($text);
var_dump($trimmed);

$trimmed trim($text" \t.");

//清除所有的\t和.
var_dump($trimmed);

$trimmed trim($hello"Hdle");
//清除所有的H、d、l和e

var_dump($trimmed);

// 清除 $binary 首位的 ASCII 控制字符
// (包括 0-31)
$clean trim($binary"\x00..\x1F");
var_dump($clean);

输出:

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(14) "Example string"
-----------------

ltrim的用法:

$trimmed ltrim($text);
var_dump($trimmed);

$trimmed ltrim($text" \t.");

//清除左端的\t和.

var_dump($trimmed);

$trimmed ltrim($hello"Hdle");
//清除左端的H、d、l和e

var_dump($trimmed);

// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)
$clean ltrim($binary"\x00..\x1F");
var_dump($clean);
输出:
string(30) "These are a few words :) ...  "
string(30) "These are a few words :) ...  "
string(7) "o World"
string(15) "Example string
"

-----------

rtrim的用法:

$trimmed rtrim($text);
var_dump($trimmed);

$trimmed rtrim($text" \t.");
//清除右端的\t和.

var_dump($trimmed);

$trimmed rtrim($hello"Hdle");

//清除右端的H、d、l和e

var_dump($trimmed);

// 删除 $binary 末端的 ASCII 码控制字符
// (包括 0 - 31)
$clean rtrim($binary"\x00..\x1F");
var_dump($clean);
输出:
string(30) "        These are a few words :) ..."
string(26) "        These are a few words :)"
string(9) "Hello Wor"
string(15) "    Example string"

posted @ 2011-11-15 17:45  南山砍柴的  阅读(2892)  评论(0编辑  收藏  举报