PHP正则表达式2不同的模式和2个不同的替换

Mal*_*xxl 2 php regex

我是关于正则表达式的新手我试图将2个或更多逗号替换为1并删除最后一个逗号.

    $string1=  preg_replace('(,,+)', ',', $string1);
    $string1= preg_replace('/,([^,]*)$/', '', $string1);
Run Code Online (Sandbox Code Playgroud)

我的问题是:用一行正则表达式有没有办法做到这一点?

Tim*_*ker 5

是的,当然有可能:

$result = preg_replace(
    '/(?<=,)   # Assert that the previous character is a comma
    ,+         # then match one or more commas
    |          # or
    ,          # Match a comma
    (?=[^,]*$) # if nothing but non-commas follow till the end of the string
    /x', 
    '', $subject);
Run Code Online (Sandbox Code Playgroud)