教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 PHP清除字符串中空白正则表达式

PHP清除字符串中空白正则表达式

发布时间:2016-12-03   编辑:jiaochengji.com
教程集为您提供PHP清除字符串中空白正则表达式等资源,欢迎您收藏本站,我们将为您提供最新的PHP清除字符串中空白正则表达式资源
在很多时候我们会碰到在字符串有会有空格,而这些空格不是我们想要的我们要怎么清除呢,下面我来介绍利用正则表达式来清除字符串中空白的办法。

先利用trim系列函数来删除左右空格

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy3154')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy3154>


<?php

trim 去除一个字符串两端空格,
rtrim 是去除一个字符串右部空格,
ltrim 是去除一个字符串左部空格。

echo trim(" 空格 ")."<br>";
echo rtrim(" 空格 ")."<br>";
echo ltrim(" 空格 ")."<br>";

?>

删除所有空格不能使用php trim()函数,因类他也只能是去除两边空闲

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9532')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy9532>


function trimall($str)//删除空格
{
 $qian=array(" "," ","t","n","r");
         $hou=array("","","","","");
 return str_replace($qian,$hou,$str); 
}

上面只能删除是一些常见的空格了,下面分享一个更具体的。

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4971')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4971>

$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 "<pre>{$str}</pre>";


中间就是利用了替换连续空格与左右空格之后再利用preg_replace替换去除重复的,然后再用另一个正则表达式[nrt]来查找任何残余的换行符(n), 回车(r), 或制表符(t) 即可。

您可能感兴趣的文章:
php怎么去除空白字符
php 正则表达式(模式修正符)
php中trim()、preg_replace()清除字符串空格与连续空格
php入门教程(二十) php常用正则表达式
PHP中正则表达式模式修饰符详解
php中常用正则表达式
PHP清除字符串中空白正则表达式
正则表达式基本函数 修饰符 元字符和需转义字
实例php正则表达式教程
常用正则表达式全集

[关闭]
~ ~