Home >Backend Development >PHP Problem >How to replace consecutive spaces in php

How to replace consecutive spaces in php

藏色散人
藏色散人Original
2021-05-27 09:15:242243browse

php替换连续空格的方法:首先创建一个PHP示例文件;然后通过“static public function merge_spaces ( $string){...}”实现替换去除多个连续空格即可。

How to replace consecutive spaces in php

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

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;
?>

推荐学习:《PHP视频教程

The above is the detailed content of How to replace consecutive 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