read array from string php - php

I have a string like this
$php_string = '$user["name"] = "Rahul";$user["age"] = 12;$person["name"] = "Jay";$person["age"] = 12;';
or like this
$php_string = '$user = array("name"=>"Rahul","age"=>12);$person= array("name"=>"Jay","age"=>12);';
I need to get the array from the string ,
Expected result is
print_r($returned);
Array
(
[name] => Rahul
[age] => 12
)
Please note that there may be other contents on the string including comments,other php codes etc

Instead of relying on some magical regular expression, I would go a slightly easier route and use token_get_all() to tokenize the string and create a very basic parser that can create the necessary structures based on both array construction methods.
I don't think many people have rolled this themselves but it's likely the most stable solution.

use a combination of eval and preg_match_all like so:
if(preg_match_all('/array\s*\(.*\)/U', $php_string, $arrays)){
foreach($arrays as $array){
$myArray = eval("return {$array};");
print_r($myArray);
}
}
That will work as long as your array doesn't contain ) but can be modified further to handle that case
or as Jack suggests use token_get_all() like so:
$tokens = token_get_all($php_string);
if(is_array($tokens)){
foreach($tokens as $token){
if($token[0] != T_ARRAY)continue;
$myArray = eval("return {$token[1]};");
print_r($myArray);
}
}

Related

Turn a string into array with PHP variables

I have a string like this:
$string = '[miniTrack, boxTrack]'
I want to turn it into an array of variables like this:
$array = [$miniTrack, $boxTrack];
So that I can perform loops and iterations through the variable. And access the variables they are referencing.
I tried eval but I can't figure out how to convert it to a PHP Variable.
I KNOW THAT THIS IS NOT IDEAL, THE STRUCTURE OF THE DATABASE THIS IS PULLING FROM CAN'T BE ADJUSTED UNFORTUNATELY
Your question starts unusually, because you show an array containing a single string that is comma-separated, rather than an array of individual strings.
You could try something like the following:
$arr = [];
$string = ['miniTrack, boxtrack'];
//split the one string into an array, trimming spaces
$vars= array_map('trim', explode(',', $string[0]));
foreach($vars as $var) {
$arr[] = $var; //add the var to the array
}
print_r($arr);
Array
(
[0] => miniTrack
[1] => boxtrack
)
And if you need to create a variable for each item, you can create "variable variables":
foreach($vars as $var) {
$my_var = $$var; //variable variable
}
It should be as easy as the following:
preg_match_all('~(\w+)~','[miniTrack, boxTrack]', $matches);
foreach($matches[1] as $var)
{
print $$var;
}
You can convert your strings to array like this. It may be not ideal but you can use try this.
$string = '[miniTrack, boxTrack]';
$string = str_replace(array('[',']'),array('', '' ), $string);
$array = explode(',',$string);
Here you can iterate your array whatever you want.

Iterate through array changing all values in an array that match a from/to associated array

I have a list of Operating systems. If someone enters something like "Ubuntu", I would like to correct that to "Linux Ubuntu". I have various other corrections like this and I'm wondering if there is an efficient way to go through an array making all these corrections?
I was thinking of having an associative array with name and key pairs; the key being the "from" field and the name being the "to". Is there a better way to do this more efficiently?
Sample array:
$os = array('Ubuntu', 'VMWare', 'CentOS', 'Linux Ubuntu');
The above values is just an example of some of the data. But essentially some of them will be correct, some will not be though, and they will need to be corrected.
What about using array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )[1] with some kind less or more sophisticated regular expression? You might need simple array of corrected (like Linux Ubuntu) values for that.
EDIT:
Code example for crystal clearance:
$regex = '/^[a-Z ]*' . $user_input . '[a-Z ]*$/';
$correct_values = {"Linux Ubuntu", "Linux Debian", "Windows XP", ...}; //const
$corrected_value = preg_grep($regex, $correct_values);
[1] http://php.net/manual/en/function.preg-grep.php
I have solved my question by going through the array checking for matching key and name pairs. The only problem I am experiencing is that the dots in the converted strings are gone and being replaced with spaces.
$commonCorrections = array("Ubuntu" => "Linux Ubuntu", "Ubuntu-12.04" => "Linux Ubuntu-12.04", "Ubuntu-10.10" => "Linux Ubuntu-10.10");
for($i = 0;$i < count($groups);$i++){
foreach($commonCorrections as $key=>$correction){
if(strtolower($key) == trim(strtolower($groups[$i]))){
$groups[$i] = $correction;
}
}
}

Create variable from print_r output [duplicate]

This question already has answers here:
How create an array from the output of an array printed with print_r?
(11 answers)
Closed 10 years ago.
How can i create variable from it's print_r output ? In other words, i'd like to know if something similar to my fictive var_import function exists in php ? var_import would be the inverse of var_export
He is a use case:
$a = var_import('Array ( [0] => foo [1] => bar )');
$output = var_export($a);
echo $output; // Array ( [0] => foo [1] => bar )
If such a function does not exist, is there a tool (or online tool) to do this ?
I am also interested to do the same with var_dump output.
EDIT: The variable is only available as a print_r output (string). To clarify what i need, imagine the folowing situation: someone posts a some sample on the internet somewhere with a print_r output. To test his code, you need to import his print_r variable into your code. This is an example where var_import would be usefull.
Amusingly the PHP manual contains an example that tries to recreate the original structure from the print_r output:
print_r_reverse()
http://www.php.net/manual/en/function.print-r.php#93529
However it does depend on whitespace being preserved. So you would need the actual HTML content, not the rendered text to pipe it back in.
Also it doesn't look like it could understand anything but arrays, and does not descend. That would be incredibly difficult as there is no real termination marker for strings, which can both contain newlines and ) or even [0] and => which could be mistaken for print_r delimiters. Correctly reparsing the print_r structure would be near impossible even with a recursive regex (and an actual parser) - it could only be accomplished by guesswork splitting like in the code linked above.. (There are two more versions there, maybe you have to try them through to find a match for your specific case.)
Why don't you use var_export instead ?
var_export(array(1, 2, 3)); // array(1, 2, 3)
You can import var_export's output with eval(), however I would recommend you to avoid this function as much as possible.
The following functions are better for exporting and importing variables:
serialize() and unserialize():
$string = serialize(array(1, 2, 3));
$array = unserialize($string); // array(1, 2, 3);
Or json_encode() and json_decode():
$string = json_encode(array(1, 2, 3));
$array = json_decode($string);
You can wrap it in an output buffer:
ob_start();
print_r(array(1,2,3));
$arr = ob_get_clean();
echo $arr;
Ok so I misunderstood the first question. I think I have another solution which actually does answer your question:
<?php
$ar = array('foo','bar');
$p = print_r($ar, true);
$reg = '/\[([0-9]+)\] \=\> ([a-z]+)/';
$m = preg_match_all($reg, $p, $ms);
$new_ar = $ms[2];
echo "Your wanted result:\n";
print_r($new_ar);
If you want to import a var_export()'s variable, you can run the eval() function.
Or if you save the contents into a file (with a return statement), you can use the return value of include() or require().
But I would rather use serialize() and unserialize() or json_encode() and json_decode().
define('EXPORT_JSON', 1);
define('EXPORT_SERIALIZE', 2);
function exportIntoFile($var, $filename, $method=EXPORT_JSON)
{
if ( $method & EXPORT_JSON )
file_put_contents( $filename, json_encode($var) );
else if ($method & EXPORT_SERIALIZE)
file_put_contents( $filename, serialize($var) );
}
function importFromFile($filename, $method=EXPORT_JSON)
{
if ( $method & EXPORT_JSON )
return json_decode( file_get_contents($filename) );
else if ($method & EXPORT_SERIALIZE)
return unserialize( file_get_contents($filename) );
}
I'm not good at regex to code the final trash removal. Here is how far I could get though:
$str = 'Array ( [0] => foo [1] => bar [2] => baz)';
$t1 = explode('(', $str);
$t2 = explode(')', $t1[1]);
$t3 = explode(' => ', $t2[0]);
unset($t3[0]);
print_r($t3);
output:
Array
(
[1] => foo [1]
[2] => bar [2]
[3] => baz
)

Read lua-like code in php

I got a question...
I got code like this, and I want to read it with PHP.
NAME
{
title
(
A_STRING
);
settings
{
SetA( 15, 15 );
SetB( "test" );
}
desc
{
Desc
(
A_STRING
);
Cond
(
A_STRING
);
}
}
I want:
$arr['NAME']['title'] = "A_STRING";
$arr['NAME']['settings']['SetA'] = "15, 15";
$arr['NAME']['settings']['SetB'] = "test";
$arr['NAME']['desc']['Desc'] = "A_STRING";
$arr['NAME']['desc']['Cond'] = "A_STRING";
I don't know how I should start :/. The variables aren't always the same.
Can someone give me a hint on how to parse such a file?
Thx
This looks like a real grammar - you should use a parser generator. This discussion should get you started.
There are a few options already made for php: a lexer generator module and this is a parser generator module.
It's not an answer but suggestion:
Maybe you can modify your input code to be compatible with JSON which has similar syntax. JSON parsers and generators are available for PHP.
http://www.json.org/
http://www.php.net/json
If the files are this simple, then rolling your own homegrown parser is probably a lot easier. You'll eventually end up writing regex with lexers anyway. Here's a quick hack example: (in.txt should contain the input you provided above.)
<pre>
<?php
$input_str = file_get_contents("in.txt");
print_r(parse_lualike($input_str));
function parse_lualike($str){
$str = preg_replace('/[\n]|[;]/','',$str);
preg_match_all('/[a-zA-Z][a-zA-Z0-9_]*|[(]\s*([^)]*)\s*[)]|[{]|[}]/', $str, $matches);
$tree = array();
$stack = array();
$pos = 0;
$stack[$pos] = &$tree;
foreach($matches[0] as $index => $token){
if($token == '{'){
$node = &$stack[$pos];
$node[$ident] = array();
$pos++;
$stack[$pos] = &$node[$ident];
}elseif($token=='}'){
unset($stack[$pos]);
$pos--;
}elseif($token[0] == '('){
$stack[$pos][$ident] = $matches[1][$index];
}else{
$ident = $token;
}
}
return $tree;
}
?>
Quick explanation: The first preg_replace removes all newlines and semicolons, as they seem superfluous. The next part divides the input string into different 'tokens'; names, brackets and stuff inbetween paranthesis. Do a print_r $matches; there to see what it does.
Then there's just a really hackish state machine (or read for-loop) that goes through the tokens and adds them to a tree. It also has a stack to be able to build nested trees.
Please note that this algorithm is in no way tested. It will probably break when presented with "real life" input. For instance, a parenthesis inside a value will cause trouble. Also note that it doesn't remove quotes from strings. I'll leave all that to someone else...
But, as you requested, it's a start :)
Cheers!
PS. Here's the output of the code above, for convenience:
Array
(
[NAME] => Array
(
[title] => A_STRING
[settings] => Array
(
[SetA] => 15, 15
[SetB] => "test"
)
[desc] => Array
(
[Desc] => A_STRING
[Cond] => A_STRING
)
)
)

php array processing question

Before I write my own function to do it, is there any built-in function, or simple one-liner to convert:
Array
(
[0] => pg_response_type=D
[1] => pg_response_code=U51
[2] => pg_response_description=MERCHANT STATUS
[3] => pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6
)
Into:
Array
(
[pg_response_type] => D
[pg_response_code] =>U51
[pg_response_description] =>MERCHANT STATUS
[pg_trace_number] =>477DD76B-B608-4318-882A-67C051A636A6
)
Just trying to avoid reinventing the wheel. I can always loop through it and use explode.
I can always loop through it and use explode.
that's what you should do.
Edit - didn't read the question right at all, whoops..
A foreach through the array is the quickest way to do this, e.g.
foreach($arr as $key=>$val)
{
$new_vals = explode("=", $val);
$new_arr[$new_vals[0]] = $new_vals[1];
}
This should be around five lines of code. Been a while since I've done PHP but here's some pseudocode
foreach element in the array
explode result on the equals sign, set limit = 2
assign that key/value pair into a new array.
Of course, this breaks on keys that have more than one equals sign, so it's up to you whether you want to allow keys to have equals signs in them.
You could do it like this:
$foo = array(
'pg_response_type=D',
'pg_response_code=U51',
'pg_response_description=MERCHANT STATUS',
'pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6',
);
parse_str(implode('&', $foo), $foo);
var_dump($foo);
Just be sure to encapsulate this code in a function whose name conveys the intent.

Categories