Home > php教程 > php手册 > body text

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

WBOY
Release: 2016-06-13 11:33:01
Original
784 people have browsed it

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

用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+([rn$])/", "1", $string);

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


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

$string = preg_replace("/s+([x20]|$)/", "1", $string);


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

$string = preg_replace("/x20+([rn]|$)/", "1", $string);


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

$string = preg_replace('/([rn])[s]+/', '1', $string);
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!