Converting Comma Separated Value to Double Quotes

2019-02-10 01:12发布

问题:

I have a comma separated value like

alpha,beta,charlie

how can i convert it to

"alpha","beta","charlie"

using a single funcion of php without using str_replace?

回答1:

Alternatively to Richard Parnaby-King's function (shorter):

function addQuotes($string) {
    return '"'. implode('","', explode(',', $string)) .'"';
}

echo addQuotes('alpha,beta,charlie'); // = "alpha","beta","charlie"


回答2:

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


回答3:

/**
 * 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"