用字符串中的逗号和空格替换3d空格

时间:2018-10-16 20:42:49

标签: php regex preg-replace

要用逗号替换字符串中的空格,我应该执行以下操作:

$result = preg_replace('/[ ]+/', ', ', trim($value));

结果:Some, example, here, for, you

但是,我只想替换3d空格,以便结果看起来像这样:

Some example here, for you

我该怎么做?

3 个答案:

答案 0 :(得分:3)

您可以使用类似的

$value = " Some example here for you ";
$result = preg_replace('/^\S+(?:\s+\S+){2}\K\s+/', ',$0', trim($value), 1);
echo $result; // => Some example here, for you

请参见PHP demoregex demo

模式详细信息

  • ^-字符串的开头
  • \S+-1个以上非空格
  • (?:\s+\S+){2}-连续两次出现
    • \s+-超过1个空格
    • \S+-1个以上非空格
  • \K-匹配重置运算符
  • \s+-(替换模式中的$0引用此子字符串)1个以上空格。

答案 1 :(得分:0)

您可以使用回调函数并控制何时替换:

[]

答案 2 :(得分:0)

尝试一下

2018/10/16 21:56:40 [error] 29187#29187: *21 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 90.252.249.6, server: www.mydomain.co.uk, request: "GET / HTTP/1.1", upstream: "http://unix:/home/my_rails_app/app/shared/unicorn.sock/", host: "www.mydomain.co.uk"
2018/10/16 21:58:02 [error] 29187#29187: *21 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 90.252.249.6, server: www.mydomain.co.uk, request: "GET / HTTP/1.1", upstream: "http://unix:/home/my_rails_app/app/shared/unicorn.sock/", host: "www.mydomain.co.uk"
2018/10/16 22:08:27 [error] 29187#29187: *26 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 90.252.249.6, server: www.mydomain.co.uk, request: "GET / HTTP/1.1", upstream: "http://unix:/home/my_rails_app/app/shared/unicorn.sock/", host: "www.mydomain.co.uk"

Test it

说明:

  • $result = preg_replace('/^([^\s]+)\s+((?1)\s+(?1))/', '\1 \2,', trim($value)); 字符串的开头
  • ^-捕获所有内容而不是空间
  • ([^\s]+)空格1或更多
  • \s+-((?1)\s+(?1))重复第一个捕获组,我们将2x间隔一个,然后捕获它。我想您可以分别捕获它们,但是重点是什么。

关于(?1)的好处是,如果您必须为捕获单词更改正则表达式,则只需将其更改1次,而不是3次。可能在这里并没有太大关系,但是我喜欢使用它...