2012-05-09 10 views
2

我很新手關於正則表達式我試圖用一個替換2個或更多的逗號並刪除最後一個逗號。PHP的正則表達式2不同的模式和2個不同的替換

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

我的問題是:有沒有辦法用一條正則表達式來做到這一點?

+0

是否要刪除最後一個逗號,如果它是唯一的逗號? – slowpoison

回答

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); 
+0

僅當它是字符串中的最後一個字符時,纔會替換最後一個逗號嗎? – slowpoison

+0

@slowpoison:你說得對,我會編輯我的答案。 –

+0

感謝您的回答和很好的解釋。會很快接受(時間限制)。 – Malixxl

0

不,這是不可能的,因爲替換是不同的,並且兩個逗號可能會或可能不會在字符串的末尾。

這就是說,preg_replace()接受的模式和替換一個數組,所以你能做到這一點,如:

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

注意,我修改了第二圖案。 希望有所幫助。

相關問題