您好,欢迎访问一九零五行业门户网

php如何替换空白

php替换空白的方法:首先通过“trim($str)”方法去掉开始和结束的空白;然后通过“preg_replace”去掉跟随别的挤在一块的空白;最后使用正则去掉非space的空白,并用一个空格代替即可。
推荐:《php视频教程》 
php替换过滤所有的空白字符与空格的例子
在php中自带的trim函数只能替换左右两端的空格,感觉在有些情况下不怎么好使,如果要将一个字符串中所有空白字符过滤掉(空格、全角空格、换行等),那么我们可以自己写一个过滤函数。
php学习str_replace函数都知道,可以批量替换的,所以我们可以用如下的源码实现替换过滤一个字符串所有空白字符了。
php源码参考:
$str = 'jkgsdgsgsdgs 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 contains\tliberal \r\n use of whitespace.\n\n";// 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('/[\n\r\t]/', ' ', $str);// echo out: 'this line contains liberal use of whitespace.'echo "{$str}";?>这个例子剥离多余的空白字符$str = 'foo o';$str = preg_replace('/\s\s+/', '', $str);// 将会改变为'foo o'echo $str;?>
以上就是php如何替换空白的详细内容。
其它类似信息

推荐信息