是否有一个函数来获取给定php字符串中的所有变量?

时间:2013-12-30 22:29:27

标签: php arrays string

我有一个脚本,其中包含一个双引号字符串(用于创建一个html表,如果它有所不同),它包含大约十几个变量。这些变量中的每一个都由while循环修改。我想在循环的每次迭代中将每组值推送到一个多维数组。现在我可以做到 array_push($my_array, $var1, $var2, $var3, ...);

但这很尴尬。

有没有办法将此字符串中的所有变量转储到我的数组中,例如: array_push($my_array, get_vars_from_string($string));

(显然,如果脚本中使用的变量在数组中开始,那将是非常好的,但是我没有编写原始版本,并且需要对程序结构进行太多更改才能进行更改。)< / p>


“字符串中的变量”是指:$table = "<td>$var1</td><td>$var2</td><funky stuff with subheadings> stuff..."

2 个答案:

答案 0 :(得分:2)

function get_vars_from_string($param)
{
     $arrfromstring=explode('$',$param);//or tokenize here
     $ret=array();//return value
      //then do the formatting and get the names of the variables,this can be done by some other functions too
     foreach($arrayfromstring as $key)
          array_push($ret,${$key});//this is the part you are looking for.
 }

我会理解我认为的标记化部分的含义。有趣的部分是${$key}。一个example

答案 1 :(得分:0)

要从字符串中获取变量,可以使用token_get_all(),但必须使用不由php处理的字符串,而是将此字符串分配给变量的原始代码行。

带有不良做法的概念验证代码:

<?php

$string_vars = array();
$double_quote_started = false;
$all_vars = array();
$table = "";
$var1 = 5;
$var2 = -5;

while($var1-- && $var2++) {

// note single quotes, this does not evaluate variables but treats everything as string
$table_str = <<<'EOT'
$table .= "<td>$var1</td><td>$var2</td><td>funky stuff</td>";
EOT;
    //evaluate the line as it was earlier
    eval($table_str);

    // since this is is first iteration, let's search our string for them
    if (empty($string_vars)) {
        foreach(token_get_all("<?php " . $table_str) as $token) {
            if (is_array($token) && $token[0] == T_VARIABLE && $double_quote_started) {
                $string_vars[] = substr($token[1],1);
            } elseif ($token === '"') {
                $double_quote_started = !$double_quote_started;     
            }
        }
    }
    $this_iteration = array();
    foreach($string_vars as $var){
        // variable variable to get content of variable
        $this_iteration[$var] = $$var;
    }
    // save this iteration vars
    $all_vars[] = $this_iteration;
}