19

My string is

$string = ",name2,name2,name3,";

I want to make it like;

$string = "name2,name2,name3";

That is, to remove first and last comma from that string, any clue as to how to accomplish this either through regex or anything else?

Thanks.

0

2 Answers 2

50

If you just want to remove the first and the last comma, you can use trim

$string = trim($string,",");
1
  • Thanks @coder for the suggestion on the usage of trim.
    – justhalf
    Commented Aug 3, 2018 at 21:14
7

You can use anchors for this:

$result = preg_replace('/^,|,$/', '', $subject);

If you want to match one or more commas at the start/end of the string:

$result = preg_replace('/^,+|,+$/', '', $subject);

And if there could be whitespace around those leading/trailing commas:

$result = preg_replace('/^[,\s]+|[\s,]+$/', '', $subject);
1
  • 1
    Thanks Tim, I didn't used your method but looks like you've got the point too. Unfortunately I've to pick only one answer as best. Thanks every one! :)
    – Uzma
    Commented Sep 3, 2013 at 11:12

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