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

How to remove spaces from string in php

王林
王林Original
2020-11-04 17:51:462031browse

php去除字符串中的空格的方法:可以利用str_replace()函数来去除字符串中的空格,如【str_replace(' ', '', 'ab    ab');】。

How to remove spaces from string in php

方法如下:

(相关学习视频推荐:java课程

str_replace() 函数替换字符串中的一些字符(区分大小写),返回带有替换值的字符串或数组。

1、正则表达式

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

2、str_repalce函数

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

3、封装函数

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

相关推荐:php培训

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