使用php替换以空格分隔的2个逗号

编程入门 行业动态 更新时间:2024-10-28 22:31:41
本文介绍了使用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个逗号

本文发布于:2023-10-18 02:58:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502876.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逗号   空格   php

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!