3 methods in php to remove Spaces between strings

  • 2021-01-22 04:55:24
  • OfStack

Type 1: Use regular

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

Second: Use the str_replace() function
<?php
echo str_replace(' ', '', 'ab    ab');
// The output  "abab'
?>

Number 3: Use the strtr() function
<?php
echo strtr('ab    ab', array(' '=>''));
//  The output  "abab"
?>

The strtr() function is a bit special to use, essentially:
<?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');
?>

Number 4: Use wrapper functions


function trimall($str)// Delete the blank space 
{
    $qian=array(" "," ","\t","\n","\r");
    $hou=array("","","","","");
    return str_replace($qian,$hou,$str); 
}


Related articles: