Jacek Kowalski
2013-09-05 0868e0642f694bf5c08951f67f5a4b7eadde041a
commit | author | age
8bd4d9 1 <?php
JK 2 class jsarray {
3     static function parse($array) {
4         $data = '<?php '.$array.' ?>';
5         $data = token_get_all($data);
6         
7         $stack = array( array() );
8         $element = NULL;
9         foreach($data as $token) {
10             if(is_array($token)) {
11                 // Ignore  < ? php  and  ? >  added above
12                 if($token[0] == T_OPEN_TAG OR $token[0] == T_CLOSE_TAG) continue;
13                 // String/int element within an array
0868e0 14                 if($token[0] == T_CONSTANT_ENCAPSED_STRING) {
8bd4d9 15                     $element = substr($token[1], 1, -1);
0868e0 16                 }
JK 17                 if($token[0] == T_LNUMBER) {
18                     $element = $token[1];
8bd4d9 19                 }
JK 20             }
21             // Nested array
22             elseif($token == '[') {
23                 array_push($stack, array());
24             }
25             // End of nested array
26             elseif($token == ']') {
0868e0 27                 // Put elements into the latest array
8bd4d9 28                 if($element !== NULL && $element !== FALSE) {
JK 29                     end($stack);
30                     $stack[key($stack)][] = $element;
31                     $element = NULL;
32                 }
33                 
34                 // Check - maybe there are no elements between ] and next ]
35                 $element = FALSE;
36                 
37                 $temp = array_pop($stack);
38                 end($stack);
39                 $stack[key($stack)][] = $temp;
40                 unset($temp);
41             }
42             // Elements separator
43             elseif($token == ',') {
0868e0 44                 // Put elements into the latest array (]] check)
8bd4d9 45                 if($element !== FALSE) {
JK 46                     end($stack);
47                     $stack[key($stack)][] = $element;
48                 }
49                 $element = NULL;
50             }
51             else
52             {
0868e0 53                 return FALSE;
8bd4d9 54             }
JK 55         }
56         
0868e0 57         if(isset($stack[0][0])) {
JK 58             return $stack[0][0];
59         } else {
60             return NULL;
61         }
8bd4d9 62     }
JK 63 }
64 ?>