Home > php教程 > php手册 > php中3种方法删除字符串中间的空格

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

WBOY
Release: 2016-06-13 09:41:12
Original
938 people have browsed it

第一种:使用正则

复制代码 代码如下:

echo preg_replace('# #', '', 'ab     ab');
//输出 "abab"
?>


第二种:使用str_replace()函数

复制代码 代码如下:

echo str_replace(' ', '', 'ab    ab');
//输出 "abab'
?>


第三种:使用strtr()函数

复制代码 代码如下:

echo strtr('ab    ab', array(' '=>''));
// 输出 "abab"
?>


strtr()函数使用上有点特别,实质上:

复制代码 代码如下:

strtr('ewb', 'web', '123') ==
strtr('ewb', array('e '=> '2', 'w' => '1', 'b' => '3')) ==
str_replace(array('e', 'w', 'b'), array('2', '1', '3'), 'ewb');
?>

第四种:使用封装函数

复制代码 代码如下:


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

Related labels:
php
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