Home  >  Article  >  Backend Development  >  3 ways to delete spaces in the middle of strings in PHP_PHP Tutorial

3 ways to delete spaces in the middle of strings in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:36:21949browse

First method: Use regular expressions

Copy the code The code is as follows:
echo preg_replace('# #', '', 'ab ab');
//Output "abab"
?>

Second: use str_replace() Function
Copy code The code is as follows:
echo str_replace(' ', '', ' ab ab');
//Output "abab'
?>

The third way: use the strtr() function
Copy code The code is as follows:
echo strtr('ab ab', array(' '=>''));
// Output "abab"
?>

The strtr() function is a bit special, essentially:
Copy code The code is as follows:
strtr('ewb', 'web', '123') ==
strtr('ewb', array('e '=> ' 2', 'w' => '1', 'b' => '3')) ==
str_replace(array('e', 'w', 'b'), array('2 ', '1', '3'), 'ewb');
?>

Fourth method: Use encapsulation function

Copy the code The code is as follows:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/739776.htmlTechArticleThe first one: Use regular expression to copy the code. The code is as follows: ?php echo preg_replace('# #', '', 'ab ab'); //Output "abab" ? Second: Use the str_replace() function to copy the code. The code is as follows: ?...
Statement:
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