【问题标题】:php curly braces into arrayphp花括号放入数组
【发布时间】:2010-04-16 03:35:22
【问题描述】:

我想检查一个打开的 .txt 文件中是否有如下打开和关闭的大括号:

file {

nextopen {
//content
}

}

不,这不是我自己的语言或任何东西,但我想说的是 nextopen 函数和括号内的所有内容,以及文件函数内部的所有内容,如果你知道我的话,将其添加到数组中意思是。所以大括号内的所有内容都将在一个数组中。如果您知道该怎么做,请回复。

数组应该是这样的:

array(
[file] => '{ nextopen { //content } }',
[nextopen] => '{ //content }'
);

【问题讨论】:

  • 不,我不知道你的确切意思。你能举个例子说明结果数组的样子吗?
  • 添加了数组的样子
  • 这可能不会像人们直觉认为的那么简单。您需要对输入进行标记。为此,您需要提供有关输入语法的更多输入。例如;标识符的标准是什么? (换行符、空格、字符等)。请参阅有关词法分析的维基百科文章,了解为什么它不是那么微不足道:en.wikipedia.org/wiki/Lexical_analysis

标签: php brackets


【解决方案1】:

基本算法如下

  1. 对于每个序列{ no-braces-here },将其放入缓冲区并替换为标识其在缓冲区中位置的幻数
  2. 重复 (1) 直到找不到更多序列
  3. 对于缓冲区中的每个条目 - 如果它包含幻数,请将每个数字替换为缓冲区中的相应字符串。
  4. 缓冲区就是我们要找的东西

在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! }
)

如果您有任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 2023-04-10
    • 2018-05-02
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多