简体   繁体   中英

PHP preg_replace() regex

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM