php - 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?
............................................................................................................................................................
解决方案
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
)
推荐阅读
- reactjs - 内置电子和反应应用程序中的空白屏幕(由于未找到文件)
- react-native - React Native 中的 require("file:///...") 使用本地资源,可能吗?
- python - (sqlite3.IntegrityError) NOT NULL 约束失败:surfers.id
- c++ - 如何将位集拆分为数组
- scala - 如何将通用测试配置应用于所有项目?
- node.js - 在 JSON 中附加每个元素的坐标
- python - 在 Python 中是否有可能有一个函数来创建许多具有递增更改名称的新变量
- c++ - 从 txt 文件初始化 uint8_t 数组
- c++ - 转换函数,std::is_base_of 和虚假的不完整类型:替换失败是一个错误
- url - 什么时候一个字符等同于它在 URL 中的百分比编码版本?