How can I make a string act as a code?

For instance, I want this string to be parsed as an array,

$config = '
    "allowable_tags" => "<p>",
    "span_regex" => null, 
    "allow_nbsp" => true, 
    "allow_class" => false
';

so,

function tidy($config = null){

    $default = array(
        "allowable_tags" => null,
        "span_regex" => null, 
        "allow_nbsp" => true, 
        "allow_class" => false
    );

    $config = array($config);

    # Loop the array.
    foreach($default as $key => $value)
    {
        # Set the variable.
        $$key = set_variable($config,$key)? set_variable($config,$key):$value;
    }

    return $allowable_tags;
}


var_dump(tidy($config));

Then I will get this as the result,

<p>

Is it feasible?

the dependant function,

function set_variable($array = array(),$key,$params = array())
{
    # If $params is not an array, let's make it array with one value of former $params.
    if(!is_array($params)) $params = array($params);
    if(!is_array($array)) parse_str($array, $array);

    # When you want a variable to return a boolean, this will return true or false.
    if(in_array('boolean', $params)) return isset($array[$key]) && $array[$key] === true ? true : false;

    # This will regard '0' as a string.
    # Return value or 0 as a string.
    elseif(in_array('zero_to_string', $params)) return isset($array[$key]) && ($array[$key] == '0') ? trim($array[$key]) : null;

    # Return null as string if 'null_to_string' is set.
    elseif(in_array('null_to_string', $params)) return isset($array[$key]) && !empty($array[$key]) ? trim($array[$key]) : 'null';

    # Check if the key is an array.
    elseif(isset($array[$key]) && !empty($array[$key]) && is_array($array[$key])) return isset($array[$key]) && !empty($array[$key]) ? $array[$key] : null;

    # This will regard '0', empty space as falsey.
    # Return value or null.
    else return isset($array[$key]) && !empty($array[$key]) ? trim($array[$key]) : null;
}
link|improve this question

1  
you can pass an array as an argument to an function, other than that i don't really see the issue. – Dagon Apr 11 at 20:29
feedback

3 Answers

up vote 2 down vote accepted

instead of making a custom function to parse the string representation of config vars to an array, why not just use an existing format such as JSON? then you can simply call json_decode() and get an array back. Also if this is for user submitted/entered config values, JSON is widely known, easy to learn and somewhat safe because no code is executed.

link|improve this answer
Thanks. I was thinking of that! I just thought the array in php5.4 is almost like json so maybe use php array instead. But I think json is easier for this case thanks! – lauthiamkok Apr 11 at 20:42
1  
@lauthiamkok, correct, in php 5.4 there are new array constructs that work like json, however to go from a string (user input, database or non php file) you would need to eval it which will execute any code within the string. at least with json and json_decode, code will not be executed during the decode process. – Jonathan Kuhn Apr 11 at 21:01
I agree with you. thanks Jonathan! :-) – lauthiamkok Apr 11 at 23:28
feedback

How do you get that string in the first place?

I'm guessing you're storing the configuration in a database or something. In which case you should use serialization, which PHP has built-in methods for.

<?php

// normal PHP array
$config = array(
    "allowable_tags" => "<p>",
    "span_regex" => null, 
    "allow_nbsp" => true, 
    "allow_class" => false
);

// array serialized as string
$string = serialize($config);

echo $string ."\n\n";
# => a:4:{s:14:"allowable_tags";s:3:"<p>";s:10:"span_regex";N;s:10:"allow_nbsp";b:1;s:11:"allow_class";b:0;}

// converting serialized string back to array
$array = unserialize($string);

print_r($array);
/*
    Array
    (
        [allowable_tags] => <p>
        [span_regex] => 
        [allow_nbsp] => 1
        [allow_class] => 
    )
*/

See it working here on ideone


EDIT

as Jonathan Kuhn recommends, json_encode() and json_decode() are also great for handling this.

link|improve this answer
How do you get that string in the first place? the string would be coming from user input. I am trying to make the code easier to for user input. But I think json is the best solution in this care. thanks. – lauthiamkok Apr 11 at 20:44
1  
Then json_decode() is your best bet, yep :) – macek Apr 11 at 20:55
yes you are right! thanks :-) – lauthiamkok Apr 11 at 23:29
feedback

I don't think it's ideal, but it is some base:

function str2array($str)
{
    $array = explode(',', $str);
    $rArray = array();
    foreach ($array as $items) {
        $i = explode('=>', $items);
        if (preg_match('/^"*(.*?)"$/', trim($i[1]), $iWithoutQuotes)) {
            $i[1] = $iWithoutQuotes[1];
        }
        $rArray[substr(trim($i[0]), 1, -1)] = trim($i[1]);
    }

    return $rArray;
}
link|improve this answer
1  
Please do not enable him to use this bad practice. PHP has several existing functions that serve his purpose. – macek Apr 11 at 20:35
1  
@macek yes. I was making a function for him. I didn't relised he could do it with json or xml or something. – Wouter J Apr 11 at 20:41
thanks for the effort, Wouter! :-) – lauthiamkok Apr 11 at 20:46
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.