使用php替换以空格分隔的2个逗号 [英] Replace 2 commas separated by space with space using php

查看:132
本文介绍了使用php替换以空格分隔的2个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,朋友们正在尝试使用php替换以空格分隔的两个逗号。这是我的代码

Hi friends am trying to replace two commas separated by space with space using php. Here is my code

假设例如,变量

 $var = "hello, welcome, , , ,"

Am使用以下代码替换逗号

Am using the below code to replace the commas in the above string.

 $output = preg_replace('/[,\s]+/', ' ', $var);

在执行上述代码时,Am得到以下输出

Am getting the following output when am executing the above code

 hello welcome

我所需的输出是

 hello, welcome

任何人都可以通过上面的代码帮助我

Can anyone help me with the above code

推荐答案

您要替换的模式是逗号,后跟一个空格后跟另一个逗号。因此,相应的正则表达式为,\s 。可以重复多次,因此将是(,\s,)+

The pattern that you intend to replace is a comma followed by a space followed by another comma. So, the corresponding regex is ",\s,". This can be repeated any number of times, so that will be "(,\s,)+".

因此,对应的PHP代码将如下所示:

So, the corresponding PHP code will look something like this:

$var = "hello, welcome, , , ,"
$output = preg_replace('/(,\s,)+/', '', $var);

编辑1:

感谢@toto提醒我此代码仅适用于偶数个逗号。典型的错误,就是在测试我的代码时不接受用户要求之外的任何其他测试用例。

Thank you @toto for reminding me that this code only works for even number of commas. Classic mistake of not taking any additional test cases than asked by the user in testing my code.

如果您要包含偶数和奇数个逗号,则您必须匹配的模式是:,(\s,)+。这是一个逗号,后跟任意数量的空格和逗号单位。

If you want to be inclusive of even and odd number of commas, then the pattern you have to match to is: ",(\s,)+". That is a comma followed by any number of space and comma units.

因此,新的PHP代码将为:

So, the new PHP code will be:

$var = "hello, welcome, , , ,"
$replacement = '';
$output = preg_replace('/,(\s,)+/', $replacement, $var);

如果您只想删除多余的逗号,请先修剪$ var的逗号并分配' ,替换为$ replacement。

If you want to just get rid of extra commas then trim the $var of commas first and assign ',' to $replacement.

这将为您提供整洁的输出。

That will give you a neat output.

这篇关于使用php替换以空格分隔的2个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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