[英]php curly braces into array
I would like to check a opened .txt file for braces that open and close like below: 我想检查打开的.txt文件中是否存在如下所示的大括号:
file {
nextopen {
//content
}
}
no this is not my own language or anything, but I want to get say the nextopen function and all the contents inside the brackets, and all the stuff from inside the file function and add it to an array if you know what i mean. 不,这不是我自己的语言也不是什么,但是我想说一下nextopen函数以及方括号内的所有内容,以及file函数内部的所有内容,如果您知道我的意思,请将其添加到数组中。 so all the content inside the braces will be in an array. 因此大括号内的所有内容都将放在一个数组中。 if you know how to do this please reply. 如果您知道该怎么做,请回复。
array should look like this: 数组应如下所示:
array(
[file] => '{ nextopen { //content } }',
[nextopen] => '{ //content }'
);
The basic algo for this is like the following 为此的基本算法如下
{ no-braces-here }
, put it in a buffer and replace with a magic number identifying its position in the buffer 对于每个序列{ no-braces-here }
,将其放在缓冲区中,并替换为标识其在缓冲区中位置的魔术数字 in php 在PHP中
class Parser
{
var $buf = array();
function put_to_buf($x) {
$this->buf[] = $x[0];
return '@' . (count($this->buf) - 1) . '@';
}
function get_from_buf($x) {
return $this->buf[intval($x[1])];
}
function replace_all($re, $str, $callback) {
while(preg_match($re, $str))
$str = preg_replace_callback($re, array($this, $callback), $str);
return $str;
}
function run($text) {
$this->replace_all('~{[^{}]*}~', $text, 'put_to_buf');
foreach($this->buf as &$s)
$s = $this->replace_all('~@(\d+)@~', $s, 'get_from_buf');
return $this->buf;
}
}
test 测试
$p = new Parser;
$a = $p->run("just text { foo and { bar and { baz } and { quux } } hello! } ??");
print_r($a);
result 结果
Array
(
[0] => { baz }
[1] => { quux }
[2] => { bar and { baz } and { quux } }
[3] => { foo and { bar and { baz } and { quux } } hello! }
)
let me know if you have any questions. 如果您有任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.