【问题标题】:PHP string presented as array to arrayPHP字符串呈现为数组到数组
【发布时间】:2015-06-01 08:12:05
【问题描述】:
$var = "['test', 'test2', 'test3']";

如何在 PHP 中创建一个可用的数组?

我试过explode($var, ",");但这似乎不起作用,除非该尝试出现问题。

【问题讨论】:

  • 将代码存储在这样的字符串中总是一个坏主意! $myArray = str_getcsv(trim($var, '[]'), ',', "'");
  • 你有什么理由不能只对它进行 json_decode 吗?
  • 啊,是的,单引号...

标签: php


【解决方案1】:

explode($var, ","); 是错误的。 explode 需要第一个参数作为分隔符,第二个参数是字符串。替换 [] 然后 explode -

$var = "['test', 'test2', 'test3']";

$var = str_replace(array('[', ']'), '', $var);
$arr = explode(',', $var);

【讨论】:

    【解决方案2】:
     [akshay@localhost tmp]$ cat test.php
     <?php 
     $var = "['test', 'test2', 'test3']";
     print_r(  json_decode(str_replace("'","\"",$var)) );
     ?>
    

    输出

     [akshay@localhost tmp]$ php test.php
     Array
     (
         [0] => test
         [1] => test2
         [2] => test3
     )
    

    【讨论】:

      【解决方案3】:

      我会说它看起来像是 json_decode 的工作,但它不是有效的 json...但是有一种方法可以使它有效:

      How to json_decode invalid JSON with apostrophe instead of quotation mark

      【讨论】:

        【解决方案4】:

        PHP 中有一个eval() 函数可以将字符串转换为PHP 语句。字符串必须是有效的 PHP 语句。

        在您的情况下,"['test', 'test2', 'test3']"; 不是有效的声明。您可以使用类似于以下语法的内容。请注意,$x 是单引号,因为双引号中的 $x 将返回值。

        $var = "['test', 'test2', 'test3'];"; eval('$x = ' . $var); print_r($x);

        【讨论】:

        • 然后祈祷这不是来自用户或第 3 方的输入。我不会为此使用 eval。
        • 是的,这是真的;如果字符串是用户输入且未正确清理,它可能容易受到攻击。
        猜你喜欢
        • 2016-01-09
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 2016-07-28
        • 2017-04-15
        • 2013-07-19
        相关资源
        最近更新 更多