大家在编写定义和用法
PHP函数trim()从字符串的两端删除空白字符和其他预定义字符。
语法
trim(str,charlist)参数 1 str为待操作的字符串,参数 2 charlist 可选,指定了想要去除的特殊符号。
如果第二个参数没给值,预设会去除下列这些字元:
<ol class="dp-xml"> <li class="alt"><span><span>" " (ASCII 32 (0x20)), an ordinary space. </span></span></li> <li><span>"t" (ASCII 9 (0x09)), a tab. </span></li> <li class="alt"><span>"n" (ASCII 10 (0x0A)), a new line (line feed). </span></li> <li><span>"r" (ASCII 13 (0x0D)), a carriage return. </span></li> <li class="alt"><span>"" (ASCII 0 (0x00)), the NUL-byte. </span></li> <li><span>"x0B" (ASCII 11 (0x0B)), a vertical tab. </span></li> </ol>
如果要去除其它字元,可以在第二个参数里设定。
例子1
<ol class="dp-xml"> <li class="alt"><span><span class="tag"></span><span class="tag-name">php</span><span> </span></span></li> <li class="alt"><span><span>$</span><span class="attribute">str</span><span> = </span><span class="attribute-value">" 使用函数trim去掉字符串两端空白字符 "</span><span>; </span></span></li> <li class="alt"><span><span>$</span><span class="attribute">str1</span><span> = </span><span class="attribute-value">trim</span><span>($str); </span></span></li> <li class="alt"><span><span>echo "处理前有".strlen($str)."个字符"; echo "</span><span class="tag"><span class="tag-name">br</span><span class="tag">/></span><span>"; </span></span></span></li> <li class="alt"><span><span>//www.phpjc.cn echo "</span><span class="tag"><span class="tag-name">br</span><span class="tag">/></span><span>"; </span></span></span></li> <li class="alt"><span><span>echo "使用trim函数处理后有".strlen($str1)."个字符"; </span></span></li> <li class="alt"><span><span class="tag">?></span><span> </span></span></li> </ol>
输出:
处理前有39个字符 使用PHP函数trim()处理后有34个字符
例子2
<ol class="dp-xml"> <li class="alt"><span><span class="tag"></span><span class="tag-name">php</span><span> </span></span></li> <li class="alt"><span><span>$</span><span class="attribute">str</span><span> = </span><span class="attribute-value">"##使用函数trim去掉字符串两端特定字符####"</span><span>; </span></span></li> <li class="alt"><span><span>$</span><span class="attribute">str1</span><span> = </span><span class="attribute-value">trim</span><span>($str,"#"); </span></span></li> <li class="alt"><span><span>//为函数trim传入第二个参数,<br>trim将删除字符串$str两端的#字符 echo $str."</span><span class="tag"><span class="tag-name">br</span><span class="tag">></span><span>"; </span></span></span></li> <li class="alt"><span><span>echo $str1; </span></span></li> <li class="alt"><span><span class="tag">?></span><span> </span></span></li> </ol>
输出:
##使用PHP函数trim()去掉字符串两端特定字符#### 使用函数trim去掉字符串两端特定字符