PHP 清除字符串中间的空格的几种方法

第一种是正则:

<?php
echo preg_replace('# #', '', 'ab     ab');
//input "abab"
?>

第二种使用str_replace()函数:

<?php
echo str_replace(' ', '', 'ab    ab');
//input "abab'
?>

第三种使用strtr()函数:

<?php
echo strtr('ab    ab', array(' '=>''));
// input "abab"
?>

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

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

参考:http://us2.php.net/manual/zh/function.strtr.php

原文地址:https://learnku.com/articles/4490/3423

posted @ 2020-11-25 11:16  imzhi  阅读(2144)  评论(0编辑  收藏  举报