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

51

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

$string = trim($string,","); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @coder for the suggestion on the usage of trim.
8

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 Comment

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! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.