search
Homephp教程php手册php 删除字符串中的空格多种方法

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

Jun 13, 2016 am 11:33 AM
phpseveral modelsdeletestringsupplyTutorialmethodspace

 本教程提供了几款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);
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool