#How to remove spaces in the middle of a string in php?
First method: Use regular expressions
The code is as follows:
<?php echo preg_replace('# #', '', 'ab ab'); //输出 "abab" ?>
Second method: Use the str_replace() function
The code is as follows:
<?php echo str_replace(' ', '', 'ab ab'); //输出 "abab' ?>
Third method: use strtr() function
The code is as follows:
<?php echo strtr('ab ab', array(' '=>'')); // 输出 "abab" ?>
The strtr() function is a bit special in use, in essence:
Code As follows:
<?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'); ?>
The fourth way: using encapsulation function
The code is as follows:
function trimall($str)//删除空格 { $qian=array(" "," ","\t","\n","\r"); $hou=array("","","","",""); return str_replace($qian,$hou,$str); }
For more related tutorials, please pay attention to php Chinese website!
The above is the detailed content of How to remove spaces from string in php. For more information, please follow other related articles on the PHP Chinese website!