Home >Backend Development >PHP Problem >How to remove spaces from string in php?
php method to remove spaces from a string: 1. Use the trim() function to remove spaces on both sides of the string; 2. Use the rtrim() and ltrim() functions to remove spaces on both sides of the string; 3. Use "str_replace(' ','', string)" to remove spaces from the string.
Recommended: "PHP Video Tutorial"
Method 1: trim() or rtrim() and ltrim() function removes spaces at both ends of a string
trim() function removes whitespace characters or other predefined characters on both sides of a string.
<?php header('content-type:text/html;charset=utf-8'); $str = " PHP去除字符串的空格! "; echo "文本为:" . trim($str); ?>
ltrim() - Removes whitespace characters or other predefined characters on the left side of a string.
rtrim() - Removes whitespace characters or other predefined characters on the right side of the string.
<?php header('content-type:text/html;charset=utf-8'); $str = " PHP去除字符串的空格! "; echo "文本为:" . rtrim(ltrim($str)); ?>
Method 2: Use str_replace() function to remove spaces
<?php echo str_replace(' ', '', 'ab ab'); //输出 "abab' ?>
Method 3: Use strtr() function to remove spaces
<?php echo strtr('ab ab', array(' '=>'')); // 输出 "abab" ?>
Method 4: Use regular expressions to remove spaces
<?php echo preg_replace('# #', '', 'ab ab'); //输出 "abab" ?>
For more programming-related knowledge, please visit: Introduction to Programming! !
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!