将字符串解析为PHP中的数组 [英] Parse string as array in PHP

查看:77
本文介绍了将字符串解析为PHP中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP新手,找不到正确的答案.

I'm new to PHP and could not find a proper answer to this.

$whatever = "array('Test','Blah')";
echo $parsed[2]; //This will be "Blah"

我想创建一个名为 $ parsed 的变量,该变量包含 $ whatever 的值,但作为有效数组而不是字符串.

I want to create a variable called $parsed which contains $whatever's value but as a valid array instead of a string.

我知道我可以通过删除数组周围的引号来创建数组,如下所示:

I'm aware I can just create the array by removing the quotation marks around it like this:

$whatever = array('Test','Blah');

但是,在我正在研究的实际代码中,这是不可能的.另外,在我的实际代码中,数组是多维的,因此涉及字符替换的操作可能不切实际,但是我不排除它是否是最佳选择.

In the actual code I'm working on, though, this isn't a possibility. Also, in my actual code, the array is multidimensional, so something involving a character replacement would probably be impractical, however I'm not ruling it out if it's the best option.

总而言之,在PHP中将字符串解析为数组的最佳方法是什么?

So to sum it up, what's the best way to go about parsing a string as an array in PHP?

推荐答案

使用 eval 函数:

请小心检查 $ whatever 变量的内容,因为可以执行任何PHP代码.

Be careful to check for the $whatever variable contents, because any PHP code can be executed.

这篇关于将字符串解析为PHP中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆