Ossi
Ossi

Reputation: 808

Remove commas except last one w preg_replace

My head is spinning, I tried to do this on my own, but cant figure it out. so once again I will turn to your guys knowledge.

These all are my possible my strings:

My head is spinning with, pregreplace
My head is spinning, with, pregreplace
My head is, spinning, with, pregreplace
My head, is, spinning, with, pregreplace

(Notice commas in above strings)

I want to have all "preg-replaced" / "string-replaced" with only one comma at the end.(Just like displayed on first example)

My head is spinning with, pregreplace

Thanks in advance ;)

Upvotes: 3

Views: 3022

Answers (2)

Colin O'Dell
Colin O'Dell

Reputation: 8647

You can use a "positive lookahead" like this:

,(?=.*,)

The lookahead is the part in parens. It basically says "only replace this comma if there's another comma later in the string.

The code would look like this:

echo preg_replace('/,(?=.*,)/', '', $str);

I tested this with RegexBuddy to confirm it works:

enter image description here

Upvotes: 8

Jonathan Rich
Jonathan Rich

Reputation: 1738

preg_replace( '/,/', '', $my_string, preg_match_all( '/,/', $my_string) - 1);

The above should do what you need.

Upvotes: 4

Related Questions