Sheriff Said Elahl
Sheriff Said Elahl

Reputation: 177

how to add double quotation character in PHP string using str_replace

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

Answers (4)

Murad Hasan
Murad Hasan

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

user5302198
user5302198

Reputation: 61

Single quotes should do the trick:

$modified = str_replace("[", '["', $NodeIDs);

Good luck to you on your project!

Upvotes: 1

Pedro Lobito
Pedro Lobito

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"]

Ideone Demo

Upvotes: 2

AbraCadaver
AbraCadaver

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

Related Questions