Reputation: 177
I have String in PHP like:
[x,y,z]
and I want to change it to
["x", "y", "z"]
I used str_replace but I can't represent the double quotation mark " in it like this
$modified = str_replace("[", "["", $NodeIDs);
I also used \ before it like java but it appears in the output. how can I do this?
Upvotes: 2
Views: 71
Reputation: 9583
Simply do this
Use trim
for removing the [
, ]
from the string, then use explode
function to get the exploded string and then implode
them.
$str = '[x,y,z]';
$arr = explode(",", trim($str, "[]"));
echo $str = '["'.implode('","', $arr).'"]'; //["x","y","z"]
Upvotes: 1
Reputation: 61
Single quotes should do the trick:
$modified = str_replace("[", '["', $NodeIDs);
Good luck to you on your project!
Upvotes: 1
Reputation: 98921
Another option is using trim
, explode
and json_encode
:
$output = json_encode(explode(',', trim('[x,y,z]', "[]")));
print_r($output);
//["x","y","z"]
Upvotes: 2
Reputation: 78994
You can use double quotes "
inside single quotes '
:
$modified = str_replace("[", '["', $NodeIDs);
Or escape them:
$modified = str_replace("[", "[\"", $NodeIDs);
Or this might be a better approach to get the desired result:
$letters = explode(',', trim($NodeIDs, '[]'));
$NodeIDs = '["' . implode('","', $letters) . '"]';
Upvotes: 3