0

以下のように開いたり閉じたりするブレースについて、開いている .txt ファイルを確認したいと思います。

file {

nextopen {
//content
}

}

いいえ、これは私自身の言語でも何でもありませんが、 nextopen 関数と括弧内のすべての内容、およびファイル関数内のすべてのものを言いたいと思います。したがって、中括弧内のすべてのコンテンツは配列になります。これを行う方法を知っている場合は、返信してください。

配列は次のようになります。

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

1 に答える 1

3

このための基本的なアルゴリズムは次のようなものです

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

ご不明な点がございましたら、お知らせください。

于 2010-04-16T10:10:52.273 に答える