0

I have a string for example: apple,orange,melon,grape,peach

I want to take the items and display them like this: "apple","orange","melon","grape","peach"

What is the most optimized way to reach this goal?

Hossj
  • 318
  • 2
  • 11
  • No regex needed. Split them by `,` and then use some string operation to put quotation marks on both ends. – jrook Apr 28 '17 at 03:46
  • See: http://stackoverflow.com/q/6102398/3933332 – Rizier123 Apr 28 '17 at 03:48
  • @hanky-panky this is not at all the same as that. I saw this before making my question. Mine is actually not an array it is a string. The answer you are referring to is only half of the way, you are assuming I know how to convert my string into an array. – Hossj Apr 28 '17 at 04:04
  • Since I am not able to post answer posting it here. If your string is of the form `word,word,word` with no whitespaces anywhere you can search for word boundary `\b` and replace with `"`. [Regex101 Demo](https://regex101.com/r/69KfIA/1/) [Ideone Demo](https://ideone.com/AZm8tl) – Rahul Apr 28 '17 at 04:05
  • @HankyPanky: This question is not about converting string to array. – Rahul Apr 28 '17 at 04:10
  • 1
    @HankyPanky yes if I knew the mix of the logics I could put 2 and 2 together. I mentioned I am looking for an optimized way of doing it. For someone who does not know either of the two, he/she would never know that they need to search first "how to split ..." and again search "implode ...". There are a ton of posts (I assume) on Stackoverflow that can be answered by mixing a few questions together. That does not mean it is a duplicate question. – Hossj Apr 28 '17 at 04:11

1 Answers1

1
$string = 'apple,orange,melon,grape,peach';
$string = explode(',', $string);
$string = '"' . implode('","', $string) . '"';
echo $string;

Compressed:

$string = 'apple,orange,melon,grape,peach';
echo '"' . implode('","', explode(',', $string)) . '"';
Enstage
  • 2,106
  • 13
  • 20