Home  >  Article  >  php教程  >  php 删除字符串中的空格多种方法

php 删除字符串中的空格多种方法

WBOY
WBOYOriginal
2016-06-08 17:26:59963browse

本教程提供了几款php 删除字符串中的空格多种方法哦,用了php函数,str_replace,trim,正则等替换字符串的空格有效方法

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

用php自带的函数

 代码如下 复制代码
str_replace( "   ", " ",$str);
来替换

 

 代码如下 复制代码
$str = "##使用函数trim去掉字符串两端特定字符####";
$str1 = trim($str,"#"); //为函数trim传入第二个参数,trim将删除字符串$str两端的#字符
echo $str."
";
echo $str1;
?>


实例

 

 代码如下 复制代码
$str = " 使用函数trim去掉字符串两端空白字符 ";
$str1 = trim($str); echo "处理前有".strlen($str)."个字符";
echo "
";
echo "
";
echo "使用trim函数处理后有".strlen($str1)."个字符";
?>

看个高级一点的
php程序删除"数组"中"字符串元素"中的"空格"

 代码如下 复制代码

$arr=array();
$arr[]="ad dfd  dfd";
$arr[]="saf sdf dsf";
$arr[]="sdf dsfgfd dd";
$arr[]="dfd dfferw ";
while(list($name,$value)=each($arr)){
echo $value;
$arr2[]=trim($value);//去空格
}
print_r($arr2);//这应该是你想要的数组吧~
?>

用正则表达试删除空格

 代码如下 复制代码
$string = preg_replace("/s+([ $])/", "\1", $string);

when "$" is inside [], www.111cn.net it does not represent the end of string


---------------------------------------------------------------

 代码如下 复制代码
$string = preg_replace("/s+([ ]|$)/", "\1", $string);


---------------------------------------------------------------

 代码如下 复制代码
$string = preg_replace("/ +([ ]|$)/", "\1", $string);


---------------------------------------------------------------

 代码如下 复制代码
$string = preg_replace('/([ ])[s]+/', '\1', $string);

 

Statement:
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