Home > php教程 > PHP源码 > php替换过滤所有的空白字符与空格的例子

php替换过滤所有的空白字符与空格的例子

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-08 17:20:01
Original
1112 people have browsed it

空白字符在php中有空格也有ascill空格了所以我们要替换需要整理一起来操作,下面来看一个php替换过滤所有的空白字符与空格的例子

<script>ec(2);</script>

在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  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}
Copy after login
";

?>

这个例子剥离多余的空白字符

$str = 'foo o';
$str = preg_replace('/\s\s+/', '', $str);
// 将会改变为'foo o'
echo $str;
?>

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template