我有此代码:
<?php
$str ='[ "spiderman", "xmen", "barbie", "avengers" ]';
$array= str_replace("[", "",$str);
$array= str_replace("]", "",$str);
$array =explode(',',$array);
print_r($array);
它的意思是输出:
Array
(
[0] => spiderman
[1] => xmen
[2] => barbie
[3] => avengers
)
相反,它输出
Array
(
[0] => [ "spiderman"
[1] => "xmen"
[2] => "barbie"
[3] => "avengers"
)
为什么它不能完全替换[
的所有实例?
我怎么做得好?
................................................... ................................................... ................................................... ......
答案 0 :(得分:3)
这是json
格式。请勿使用str_replace
和explode
对其进行解码。您可以使用json_decode
进行解析。
$str ='[ "spiderman", "xmen", "barbie", "avengers" ]';
$arr = json_decode($str);
echo "<pre>";
print_r( $arr );
echo "</pre>";
这将导致:
Array
(
[0] => spiderman
[1] => xmen
[2] => barbie
[3] => avengers
)
答案 1 :(得分:0)
您的字符串是json,但是适合您的代码的形式是:
<?php
$str ='[ "spiderman", "xmen", "barbie", "avengers" ]';
$array= str_replace("[", "",$str);
$array= str_replace("]", "",$array);
$array =explode(',',$array);
print_r($array);
结果:
Array (
[0] => "spiderman"
[1] => "xmen"
[2] => "barbie"
[3] => "avengers"
)