如何添加字符到字符串


How to add characters into string

我有一个字符串

$str = "a,b,c,d,e"; 

我想把字符串转换为:

$str_convert = "'a','b','c','d','e'";

我该怎么办?

试试我的解决方案:

<?php
$str = "a,b,c,d,e";
$arr = explode(',',$str);
foreach ($arr as &$value) {
    $value = "'$value'";
}
$str_convert= implode(',', $arr);
echo $str_convert;

像这样:

$str = "a,b,c,d,e";
$items = split(",", $str);
$convert_str = "";
foreach ($items as $item) {
   $convert_str .= "'$item',";
}
$convert_str = rtrim($convert_str, ",");
print($convert_str);

如果您想要使用函数式编程编码风格的不同解决方案,请参考:

<?php
$str = 'a,b,c,d,e';
$add_quotes = function($str, $func) {
    return implode(',', array_map($func, explode(',', $str)));
};

print $add_quotes(
    $str,
    function ($a) {
        return "'$a'";
    }
);