2

私は正規表現についてかなり初心者です。2つ以上のコンマを1つに置き換え、最後のコンマを削除しようとしています。

    $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

いいえ、置換が異なり、2 つのカンマが文字列の末尾にある場合とない場合があるため、それは不可能です。

つまりpreg_replace()、パターンと置換の配列を受け入れるので、次のようにすることができます。

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

2 番目のパターンを変更したことに注意してください。それが役立つことを願っています。

于 2012-05-09T06:05:24.943 に答える