Home >Backend Development >PHP Problem >How to remove spaces from string in php?

How to remove spaces from string in php?

青灯夜游
青灯夜游Original
2020-11-06 16:17:073137browse

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.

How to remove spaces from string in php?

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(&#39;content-type:text/html;charset=utf-8&#39;);
$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(&#39;content-type:text/html;charset=utf-8&#39;);
$str = " PHP去除字符串的空格! ";
echo "文本为:" . rtrim(ltrim($str));
?>

Method 2: Use str_replace() function to remove spaces

<?php
echo str_replace(&#39; &#39;, &#39;&#39;, &#39;ab    ab&#39;);
//输出 "abab&#39;
?>

Method 3: Use strtr() function to remove spaces

<?php
echo strtr(&#39;ab    ab&#39;, array(&#39; &#39;=>&#39;&#39;));
// 输出 "abab"
?>

Method 4: Use regular expressions to remove spaces

<?php
echo preg_replace(&#39;# #&#39;, &#39;&#39;, &#39;ab     ab&#39;);
//输出 "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!

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