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

Replace 3d whitespace with comma and whitespace in string

要在字符串中用逗号和白色space替换白色space,我应该这样做:

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

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

但是,我只想替换 3d 白色 space,这样结果看起来像这样:

Some example here, for you

我该怎么做?

你可以使用像

这样的东西
$value = " Some example here for you ";
$result = preg_replace('/^\S+(?:\s+\S+){2}\K\s+/', ',[=10=]', trim($value), 1);
echo $result; // => Some example here, for you

参见PHP demo and the regex demo

图案详情

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

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

<?php

$string = 'Some example here for you';
$i = 0;
$string = preg_replace_callback('/\s+/',function($m) use(&$i){
    $i++;
    if($i == 3) {
        return ', ';
    }
    return ' ';
},$string);

echo $string;

试试这个

$result = preg_replace('/^([^\s]+)\s+((?1)\s+(?1))/', ' ,', trim($value));

Test it

解释:

  • ^ 字符串开头
  • ([^\s]+) - 捕捉一切不是 space
  • \s+ space 1个或更多
  • ((?1)\s+(?1)) - (?1) 重复第一个捕获组,我们用 space 重复两次,然后捕获它。我想您可以分别捕获它们,但这有什么意义。

(?{n}) 的好处是,如果您必须更改捕获单词的正则表达式,您只需更改它 1 次,而不是 3 次。可能在这里并不重要,但我喜欢用它...