Converting Comma Separated Value to Double Quotes comma separated string

女生的网名这么多〃 提交于 2019-11-29 21:55:47

问题


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"



来源:https://stackoverflow.com/questions/11340334/converting-comma-separated-value-to-double-quotes-comma-separated-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!