将逗号分隔值转换为双引号以逗号分隔的字符串

时间:2012-07-05 08:14:58

标签: php string double comma

我有一个逗号分隔值,如

alpha,beta,charlie

如何将其转换为

"alpha","beta","charlie"

使用php的单一功能而不使用str_replace?

3 个答案:

答案 0 :(得分:14)

Richard Parnaby-King的功能(更短):

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

怎么样

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

功能:

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