Php 针对多余的空白,但保留新行

Php 针对多余的空白,但保留新行,php,regex,string,Php,Regex,String,我试图在数据库迁移期间清理一些字符串,并删除多余的空白 An example of a string would be like this and for some reason has empty spaces in the beginning of new lines. 有时新行开头只有1个空格 我需要在单词和新行之间保留空格 我尝试了以下方法: $string=str_replace(“”,,$string);(仅替换部分,还不

我试图在数据库迁移期间清理一些字符串,并删除多余的空白

    An example of a string would be like this
          and for some reason has empty spaces
                in the beginning of new lines.
有时新行开头只有1个空格

我需要在单词和新行之间保留空格

我尝试了以下方法:

$string=str_replace(“”,,$string);(仅替换部分,还不够)

$string=preg_replace('/\s+/','$string);(删除换行符)

我想到的最贴切的东西是这个怪物:

        $string = str_replace('    ', ' ', $string);
        $string = str_replace('   ', ' ', $string);
        $string = str_replace('  ', ' ', $string);
        $string = str_replace('  ', ' ', $string);
        $string = str_replace(' ', ' ', $string);
        $string = str_replace(' ', ' ', $string);
        $string = str_replace('\r ', '\r', $string);
        $string = str_replace('\n ', '\n', $string);
它删除了大部分空白,保留了新行,但仍然在新行的开头保留了1个额外的空间

最好的方法是什么

你可以用这个

preg_replace('/\s+/S', " ", $string);
这将用一个空格、制表符和新行替换所有多个空格、制表符和新行。

您可以使用:

$string = preg_replace('/[ ]+/', ' ', $string);
它应该用一个空格替换多个空格(而不是像换行符这样的空白)

编辑

如果需要从行首删除空格,可以使用以下模式再次运行
preg\u replace

  $string = preg_replace('/^[ ]+/m', '', $string);

这将在行首搜索一个或多个空格,替换为空字符串。

您可以使用交替选项,从行首匹配1+水平空格字符,或在单词之间匹配1个水平空格字符,并匹配以下字符

然后替换为空字符串

^\h+\h\K\h+

解释

  • ^\h+
    断言字符串的开头,并匹配一个或多个水平空白字符
  • |
  • \h\K\h+
    匹配水平空白字符,忘记匹配的内容,然后匹配一个或多个水平空白字符
|


如果您只想从字符串开始匹配,您可以使用
^\h+

谢谢,这基本上是以一种优雅的方式做同样的事情!你知道我怎样才能使它也以出现在特征线之后的一个空格为目标吗?我试过了,但它并没有保留这些特征线