Converting comma-separated values ​​to double quotes

I have a comma separated value like

alpha,beta,charlie 

how can i convert it to

 "alpha","beta","charlie" 

using a single php function without using str_replace?

+6
source share
3 answers

As an alternative to the Richard Parnaby King function (in short):

 function addQuotes($string) { return '"'. implode('","', explode(',', $string)) .'"'; } echo addQuotes('alpha,beta,charlie'); // = "alpha","beta","charlie" 
+12
source
 /** * Take a comma separated string and place double quotes around each value. * @param String $string comma separated string, eg 'alpha,beta,charlie' * @return String comma separated, quoted values, eg '"alpha","beta","charlie"' */ function addQuote($string) { $array = explode(',', $string); $newArray = array(); foreach($array as $value) { $newArray[] = '"' . $value . '"'; } $newString = implode(',', $newArray); return $newString; } 

echo addQuote('alpha,beta,charlie'); // results in: "alpha","beta","charlie"

0
source

What about

  <?php $arr = spliti(",","alpha,beta,charlie"); for($i=0; $i < sizeof($arr); $i++) $var = $var . '"' . $arr[$i] . '",'; //to avoid comma at the end $var = substr($var, 0,-1); echo $var; ?> 

with function:

 <?php function AddQuotes($str){ $arr = spliti(",",$str); for($i=0; $i < sizeof($arr); $i++) $var = $var . '"' . $arr[$i] . '",'; //to avoid comma at the end $var = substr($var, 0,-1); echo $var; } AddQuotes("alpha,beta,charlie"); ?> 
0
source

Source: https://habr.com/ru/post/919728/


All Articles