首页 > 解决方案 > Str_replace not replacing completely

问题描述

I have this code:

<?php
$str ='[ "spiderman", "xmen", "barbie", "avengers" ]';

$array= str_replace("[", "",$str);
$array= str_replace("]", "",$str);

$array =explode(',',$array);


print_r($array);

It is meant to output:

Array
(
    [0] =>  spiderman
    [1] =>  xmen
    [2] =>  barbie
    [3] =>  avengers
)

But rather it outputs

Array
(
    [0] => [ "spiderman"
    [1] =>  "xmen"
    [2] =>  "barbie"
    [3] =>  "avengers" 
)

Why didn't it completely replace all instances of [? How do I do it well? ............................................................................................................................................................

标签: phparrays

解决方案


This is a json format. Dont use str_replace and explode to decode it. You can use json_decode to parse.

$str ='[ "spiderman", "xmen", "barbie", "avengers" ]';
$arr = json_decode($str);

echo "<pre>";
print_r( $arr );
echo "</pre>";

This will result to:

Array
(
    [0] => spiderman
    [1] => xmen
    [2] => barbie
    [3] => avengers
)

推荐阅读