[英]php curly braces into array
我想检查打开的.txt文件中是否存在如下所示的大括号:
file {
nextopen {
//content
}
}
不,这不是我自己的语言也不是什么,但是我想说一下nextopen函数以及方括号内的所有内容,以及file函数内部的所有内容,如果您知道我的意思,请将其添加到数组中。 因此大括号内的所有内容都将放在一个数组中。 如果您知道该怎么做,请回复。
数组应如下所示:
array(
[file] => '{ nextopen { //content } }',
[nextopen] => '{ //content }'
);
为此的基本算法如下
{ no-braces-here }
,将其放在缓冲区中,并替换为标识其在缓冲区中位置的魔术数字 在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;
}
}
测试
$p = new Parser;
$a = $p->run("just text { foo and { bar and { baz } and { quux } } hello! } ??");
print_r($a);
结果
Array
(
[0] => { baz }
[1] => { quux }
[2] => { bar and { baz } and { quux } }
[3] => { foo and { bar and { baz } and { quux } } hello! }
)
如果您有任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.