Home > php教程 > PHP源码 > php中3种方法删除字符串中间的空格_php实例

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

PHP中文网
Release: 2016-05-25 17:11:40
Original
1200 people have browsed it

这篇文章主要介绍了php中3种方法删除字符串中间的空格,需要的朋友可以参考下

第一种:使用正则

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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template