Reputation: 808
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
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:
Upvotes: 8
Reputation: 1738
preg_replace( '/,/', '', $my_string, preg_match_all( '/,/', $my_string) - 1);
The above should do what you need.
Upvotes: 4