我有一个逗号分隔的值,比如
alpha,beta,charlie
我怎样才能将其转换为
"alpha","beta","charlie"
在不使用 str_replace 的情况下使用 php 的单个功能?
替代 Richard Parnaby-King 的函数(更短):
function addQuotes($string) {
return '"'. implode('","', explode(',', $string)) .'"';
}
echo addQuotes('alpha,beta,charlie'); // = "alpha","beta","charlie"
/**
* 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"
关于什么
<?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");
?>