Home php教程 php手册 PHP清除字符串中空白正则表达式

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

May 25, 2016 pm 04:55 PM

在很多时候我们会碰到在字符串有会有空格,而这些空格不是我们想要的我们要怎么清除呢,下面我来介绍利用正则表达式来清除字符串中空白的办法。

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

 代码如下 复制代码


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

echo trim(" 空格 ")."
";
echo rtrim(" 空格 ")."
";
echo ltrim(" 空格 ")."
";

?>

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

 代码如下 复制代码


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

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

 代码如下 复制代码

$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 "

{$str}
Copy after login
";


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



永久链接:

转载随意!带上文章地址吧。

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)