如何替换每一秒的空白? [英] How to replace every second white space?

查看:33
本文介绍了如何替换每一秒的空白?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 preg_replace,"替换每隔一个空格.并输入这样的字符串:

I want replace every second white space with "," using preg_replace. And input string like this:

$string = 'a b c d e f g h i';

应该产生这样的输出:

a b,c d,e f,g h,i

谢谢

推荐答案

可以组合使用 explodearray_chunkarray_map内爆:

You can use a combination of explode, array_chunk, array_map and implode:

$words = explode(' ', $string);
$chunks = array_chunk($words, 2);
$chunks = array_map(function($arr) { return implode(' ', $arr); }, $chunks);
$str = implode(',', $chunks);

但它假设每个单词都由一个空格分隔.

But it assumes that each word is separated by a single space.

另一个可能更简单的解决方案是使用 preg_replace 像这样:

Another and probably easier solution is using preg_replace like this:

preg_replace('/(\S+\s+\S+)\s/', '$1,', $string)

模式 (\S+\s+\S+)\s 匹配一个或多个非空白字符 (\S+) 后跟一个或多个的任何序列空格字符 (\s+),后跟一个或多个非空格字符,后跟一个空格字符,并用逗号替换最后一个空格.前导空格将被忽略.

The pattern (\S+\s+\S+)\s matches any sequence of one or more non-whitespace characters (\S+), followed by one or more whitespace characters (\s+), followed by one or more non-whitespace characters, followed by one whitespace character, and replaces the last whitespace by a comma. Leading whitespace will be ignored.

所以匹配将在这种情况下:

So the matches will be in this case:

a b c d e f g h i
\__/\__/\__/\__/

然后将它们替换如下:

a b,c d,e f,g h,i

这篇关于如何替换每一秒的空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆