3

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

2
  • 3
    strrpos, substr, str_replace, that's all. Commented Feb 20, 2012 at 22:37
  • Both works great, I will select answer in next 10 minutes. I noticed on my data, that I also have multi lines ie like this:My head is spinning with, pregreplace (Shoot I cant edit multi lines here... but basically need to make it single line as well with this same script.
    – Ossi
    Commented Feb 20, 2012 at 23:06

2 Answers 2

8

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

1
  • 1
    you're missing pattern delimiters in the first preg_replace argument. or are they optional these days? am i showing my age here? otherwise, +1. Commented Feb 20, 2012 at 22:47
4
preg_replace( '/,/', '', $my_string, preg_match_all( '/,/', $my_string) - 1);

The above should do what you need.

3
  • Would strrpos be a more-efficient method than preg_match_all in this case? Commented Feb 20, 2012 at 22:54
  • Wish I could give 2 answer credits... I gave you a bump anyhow... Thanks
    – Ossi
    Commented Feb 20, 2012 at 23:18
  • 1
    @ColinO'Dell Yes, I originally wrote the solution using the string functions, but since the request was specifically for using preg_replace I provided that solution. Commented Feb 21, 2012 at 14:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.