使用trim函数去除空格!

输入:" hello world ! "
如何用 trim只去除!号后面的空格?又能否只把中间的其余空格去除?

trim()只去除前后的空格,中间的不会去掉
如果想去掉中间的,直接用replace(" ","")替换

$str = ' hello world! ';
echo preg_replace('# #', '', $str);
echo '<br />';
echo str_replace(' ', '', $str);
echo '<br />';
echo strtr($str, array(' '=>''));

//helloworld!

//helloworld!

//helloworld!


什么语言,建议改用正则

trim方法不能达到你的需求,可以看其方法说明:同时去掉最开始和结尾的空格。

 If this String object represents an empty character sequence, or the first and last characters of character 

str.replaceAll(" ","");

一般都使用replaceAll来替换字符串内的所有空格

trim达不到你想要的要求
只能用replaceAll(" ","")来把你的空格删掉