Replace 2 commas separated by space with space usi

2019-02-21 08:16发布

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

Suppose for example am having variable like

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

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

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

Am getting the following output when am executing the above code

 hello welcome

My required output is

 hello, welcome

Can anyone help me with the above code

4条回答
小情绪 Triste *
2楼-- · 2019-02-21 08:53

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,)+".

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

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

Edit 1:

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.

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.

So, the new PHP code will be:

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

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.

查看更多
We Are One
3楼-- · 2019-02-21 09:01

You can try by the following solution:

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

$result = explode(',', $var);

$result = $result[0]. ', '. $result[1];

echo $result;
查看更多
闹够了就滚
4楼-- · 2019-02-21 09:04

Try this option:

$var = "hello, welcome, , , , ,";
$output = preg_replace('/,\s(?=[,])|,$/', '', $var);

hello, welcome

Demo

This uses a lookahead to target only commas that are followed by a space and a comma, or by the end of the string.

查看更多
Melony?
5楼-- · 2019-02-21 09:10
preg_replace('/(,\s?)+$/', '', "hello, welcome, , , ,");

Basically, match every contiguous sequence of , until the end of the string.

see https://regex101.com/r/rSp90e/1 for a demo.

查看更多
登录 后发表回答