Replace 2 commas separated by space with space using php

后端 未结 4 775
故里飘歌
故里飘歌 2021-01-17 06:10

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         


        
4条回答
  •  花落未央
    2021-01-17 06:30

    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.

提交回复
热议问题