PHP trim() 函数使用详解
先看trim的详细介绍,要仔细一点阅读,后面有指出容易忽视的地方:
PHP 字符串去除
用于去除字符串首尾空白等特殊符号或指定的字符。
相关函数如下:
- trim():去除字符串 首尾 空白等特殊符号或指定字符序列
- ltrim():去除字符串 首 空白等特殊符号或指定字符序列
- rtrim():去除字符串 尾 空白等特殊符号或指定字符序列
- chop():同rtrim()
去除字符串首尾空白等特殊符号或指定字符序列。
语法:
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 "
";echo trim($trimmed, "Hdle"); //输出"o Wor"echo "
";echo trim($text, "Hdle"); //输出"o World"?>
从这个例子可以看出,trim() 函数将不会去除非首尾的 charlist 。
----------------------------------------------------------------------------------------------------------
但是,如果你碰到这样的情况,结果会是什么样的?要除去的charlist中间存在和待处理的字符串中有相同的情况下。
她会返回为: index.php?user=useredi
为什么呢?
因为trim第二个参数是charlist,而不是一个字符串整体,所有,charlist中含有的字符都会在结尾被除去!
比如:echo rtrim('abcdefg','cg'); //abcdef
那么我们如何做到返回index.php?user=useredit呢?
function trim_str($content, $str){
$content= trim($content);
$str= str_replace("\\", "\\\\", $str);
$str= str_replace('/', '\\/', $str);
$start_pattern = "/^($str)+/i";
$end_pattern = "/($str)+$/i";
return trim(preg_replace($end_pattern, '', preg_replace($start_pattern,'',$content)));
}
echo trim_str('.htmlindex.php?user=useredit','.html'); //index.php?user=useredit
echo '
';
echo trim_str('index.php?user=useredit.html','.html'); //index.php?user=useredit
echo '
';
echo trim_str('index.php?user=useredit.你好','.你好'); //index.php?user=useredit
echo '
';
echo trim_str('index.php?use.htmlr=useredit','.html'); //index.php?use.htmlr=useredit
这个就可以把charlist当做完整的去除字符串参数来用了!希望对你有用!
12月31
2012-01-13 10:59:08
不错 学习了 http://www.jinjingwang.com 天猫网