2

我对正则表达式很陌生,我正在尝试将 2 个或多个逗号替换为一个并删除最后一个逗号。

    $string1=  preg_replace('(,,+)', ',', $string1);
    $string1= preg_replace('/,([^,]*)$/', '', $string1);

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

4

2 回答 2

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);
于 2012-05-09T06:07:49.670 回答
0

不,这是不可能的,因为替换是不同的,并且两个逗号可能在也可能不在字符串的末尾。

也就是说,preg_replace()接受一系列模式和替换,因此您可以这样做:

preg_replace(array('/,,+/', '/,$/'), array(',', ''), $string1);

请注意,我修改了第二个模式。希望有帮助。

于 2012-05-09T06:05:24.943 回答