0

I have a string

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

And I want convert string as:

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

What should I do?

3 Answers 3

2

Try my solution:

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

$str_convert= implode(',', $arr);
echo $str_convert;
Sign up to request clarification or add additional context in comments.

Comments

1

Like this:

$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);

Comments

1

If you would like a different solution using functional programming coding style, here it is:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.