Home  >  Article  >  Backend Development  >  How to remove spaces in string in php

How to remove spaces in string in php

藏色散人
藏色散人Original
2021-02-28 10:07:585811browse

php method to remove spaces in a string: 1. Use regular expressions to delete spaces in the middle of the string and remove spaces at the beginning and end of the string; 2. Use str_replace and strtr functions to delete spaces in the middle of the string; 3. Use the trim function to remove spaces from both ends of a string.

How to remove spaces in string in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

3 methods to delete strings in php The space in the middle

The first way: use regular

The code is as follows:

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

The second way: use the str_replace() function

code As follows:

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

Third method: use strtr() function

The code is as follows:

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

The strtr() function is a bit special in use, in essence:

The code is as follows:

<?php
strtr(&#39;ewb&#39;, &#39;web&#39;, &#39;123&#39;) ==
strtr(&#39;ewb&#39;, array(&#39;e &#39;=> &#39;2&#39;, &#39;w&#39; => &#39;1&#39;, &#39;b&#39; => &#39;3&#39;)) ==
str_replace(array(&#39;e&#39;, &#39;w&#39;, &#39;b&#39;), array(&#39;2&#39;, &#39;1&#39;, &#39;3&#39;), &#39;ewb&#39;);
?>

The fourth way: use the encapsulated function

The code is as follows:

function trimall($str)//删除空格
{
    $qian=array(" "," ","\t","\n","\r");
    $hou=array("","","","","");
    return str_replace($qian,$hou,$str); 
}

[Recommended learning: "PHP Video Tutorial" 】

How to remove the leading and trailing spaces of a string in PHP

The first method: through the function that comes with PHP

<?php
/*
trim 去除一个字符串两端空格,
rtrim 是去除一个字符串右部空格,
ltrim 是去除一个字符串左部空格。
*/
?>
<?php
echo trim(" 空格 ")."<br>";
echo rtrim(" 空格 ")."<br>";
echo ltrim(" 空格 ")."<br>";
?>

The second method: replace by regular expression, more powerful

php removes spaces at the beginning and end of the string (including full-width)

The code is as follows:

<?
$str="     脚本之家 www.jb51.net     ";
$str = mb_ereg_replace(&#39;^( | )+&#39;, &#39;&#39;, $str);
$str = mb_ereg_replace(&#39;( | )+$&#39;, &#39;&#39;, $str);
echo mb_ereg_replace(&#39;  &#39;, "\n  ", $str);
?>

The above is the detailed content of How to remove spaces in 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