0
votes

I am getting a dynamic value in the following format, can anyone help me how to get rid of extra chars using preg_replace()?

case1)  $string='""14""';  
case2)  $string='""string1""';  
case3)  $string='"[\"string1\", \"string2\"]"';  
case4) $string='"[\"string1\", \"string21\", \"string3\"]"';  

here i want to get rid of only " [ \ ] but not comma ',', so if it is one string i will get only double quotes but if it is more than one i will get in the farm comma separated.

i need following output.
case1) 14
case2) string1
case3) string1,string2
case4) string1,string21,string3

Thanks in advance for your help...

1
looks like mangled json... wouldn't you be better off fixing whatever's generating this?Marc B
Can you please added expected output for each given input?Brandon Wamboldt
I need the following out put.user1642408
sorry i just edited for the output that i needuser1642408
@user1642408: Pay attention to MarcB's comment: it does look a lot like you're attempting to parse JSON data using regex. Try var_dump(json_decode($string)); in case 4, for example... you might be surprized at how easy things can beElias Van Ootegem

1 Answers

0
votes

As others have mentioned, this looks like mangled JSON. But just calling json_decode on it won't work because of the extra quotes around the string. Try stripping them like this:

$str = substr($str, 1, -1);
$vals = json_decode($str);
print_r($vals);

if you really want it formatted exactly as you mentioned in your question, you can continue

$str = implode(',', $vals);
print_r($str);