Home > Backend Development > PHP Problem > How to remove spaces in the middle of a string in php?

How to remove spaces in the middle of a string in php?

coldplay.xixi
Release: 2023-03-02 21:32:01
Original
3006 people have browsed it

php method to delete spaces in the middle of a string: 1. Use the regular method, the code is [echo preg_replace('# #', '', 'ab ab')]; 2. Use [str_replace()] Function method, the code is [echo str_replace(' ')].

How to remove spaces in the middle of a string in php?

php method to delete spaces in the middle of a string:

First: use regular expressions

The code is as follows:

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

Second type: Use str_replace() function

The code is as follows:

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

Third method: Use the strtr() function

The code is as follows:

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

strtr()The use of the function is a bit special, 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;);
?>
Copy after login

Fourth method: Use encapsulation function

The code is as follows:

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

Related learning recommendations:PHP programming from entry to proficiency

The above is the detailed content of How to remove spaces in the middle of a string in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template