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

How to remove extra spaces in php

藏色散人
藏色散人Original
2020-08-19 09:12:473038browse

php去除多余空格的方法:首先创建一个PHP示例文件;然后使用语句“preg_replace('/\s(?=\S)/','',$str);”去除指定字符串中多余的空格即可。

How to remove extra spaces in php

推荐:《PHP视频教程

PHP去除多余空格 多个连续空格只保留一个

/**
* 多个连续空格只保留一个
*
* @param string $string 待转换的字符串
* @return unknown
*/
static public function merge_spaces ( $string )
{
    return preg_replace ( "/\s(?=\s)/","\\1", $string );
}<br><br>出处:http://www.open-open.com/code/view/1420711244390 //Delphi有一个函数可以将多余的字符串替换一次,保留其中一个。php就复杂多了,而且我对正则也不是太了解。<br><br>代码经我修改后,达到了我想要的目的:除两个连续空格外,其它的单个不连续空格均被替换。
<?php
header(&#39;Content-type: text/html; charset=utf-8&#39;);
$str = "PHP去除 多余空格 多个连续 空格只保留一个";
$str = preg_replace(&#39;/\s(?=\S)/&#39;,&#39;&#39;,$str); //只保留一个空格,还有(?=\s)这个写法叫“断言”
echo $str;
?>

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