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
$va
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.
You can try by the following solution:
$var = "hello, welcome, , , ,";
$result = explode(',', $var);
$result = $result[0]. ', '. $result[1];
echo $result;
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.
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.