如何使字符串充当代码?
例如,我希望将此字符串解析为数组,
$config = '
"allowable_tags" => "<p>",
"span_regex" => null,
"allow_nbsp" => true,
"allow_class" => false
';
所以,
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));
然后我会得到这个结果,
<p>
可行吗?
依赖函数,
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;
}