最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
php替换过滤所有的空白字符与空格的例子
时间:2022-06-24 16:55:08 编辑:袖梨 来源:一聚教程网
在php中自带的trim函数只能替换左右两端的空格,感觉在有些情况下不怎么好使,如果要将一个字符串中所有空白字符过滤掉(空格、全角空格、换行等),那么我们可以自己写一个过滤函数。
php学习str_replace函数都知道,可以批量替换的,所以我们可以用如下的源码实现替换过滤一个字符串所有空白字符了。
php源码参考:
$str = 'jkgsd
gsgsdgs  gsdg gsd';
echo myTrim($str);
function myTrim($str)
{
 $search = array(" "," ","n","r","t");
 $replace = array("","","","","");
 return str_replace($search, $replace, $str);
}
?>
运行代码,页面输出:jkgsdgsgsdgsgsdggsd,完美实现了我们想要的效果。
完成这些可以使用PHP的正则表达式来完成
下例可以去除额外Whitespace
$str = " This line containstliberal rn use of whitespace.nn";
// First remove the leading/trailing whitespace
//去掉开始和结束的空白
$str = trim($str);
// Now remove any doubled-up whitespace
//去掉跟随别的挤在一块的空白
$str = preg_replace('/s(?=s)/', '', $str);
// Finally, replace any non-space whitespace, with a space
//最后,去掉非space 的空白,用一个空格代替
$str = preg_replace('/[nrt]/', ' ', $str);
// Echo out: 'This line contains liberal use of whitespace.'
echo "
{$str}";
?>
这个例子剥离多余的空白字符
$str = 'foo o';
$str = preg_replace('/ss+/', '', $str);
// 将会改变为'foo o'
echo $str;
?>
相关文章
- 火山的女儿战斗技如何选择 10-31
- 洛克王国世界远行商人在哪里-远行商人位置及售卖物品 10-31
- 鸣潮仇远角色强度怎么样 10-31
- 永恒之塔2基纳币如何获取 10-31
- 异环安魂曲角色怎么样 10-31
- 二重螺旋达芙涅有什么技能 10-31
 
             
                                 
                                 
                                 
                                 
                                            
                                         
                                            
                                         
                                            
                                         
                                            
                                         
                                            
                                         
                                            
                                         
                                            
                                         
                                            
                                         
                                            
                                        