0

バルクテンプレート(1つのファイルに複数のテンプレートエントリ)をロードし、それに応じて保存できるテンプレート風のシステムがあります。問題は、現在のアプローチがを使用していることでpreg_replace()ありeval、それは本当にエラーが発生しやすいです。このエラーの例は、正規表現を壊して解析エラーを作成する不適切に配置された文字である可能性があります。

Parse error: syntax error, unexpected '<' in tsys.php: eval()'d code

これを行うコードは次のとおりです。

// Escaping
$this->_buffer = str_replace( array('\\', '\'', "\n"), array('\\\\', '\\\'', ''), $this->_buffer);

// Regular-expression chunk up the input string to evaluative code
$this->_buffer = preg_replace('#<!--- BEGIN (.*?) -->(.*?)<!--- END (.*?) -->#', "\n" . '$this->_tstack[\'\\1\'] = \'\\2\';', $this->_buffer);

// Run the previously created PHP code
eval($this->_buffer);

このバルクテンプレートのサンプルファイルは次のようになります。

<!--- BEGIN foo -->
<p>Some HTML code</p>
<!--- END foo -->

<!--- BEGIN bar -->
<h1>Some other HTML code</h1>
<!--- END bar -->

この入力でコードを実行すると、次の$this->_tstack2つの要素が与えられます。

array (
  'foo' => "<p>Some HTML code</p>",
  'bar' => "<h1>Some other HTML code</h1>",
);

これは予想される動作ですが、の必要性をなくすことができる方法を探していevalます。

4

2 に答える 2

1

あなたはそれをするために使うことができますpreg_match_all

// Remove CR and NL
$buffer = str_replace(array("\r", "\n"), '', $this->_buffer);

// Grab interesting parts
$matches = array();
preg_match_all('/\?\?\? BOT (?P<group>[^ ]+) \?\?\?(?P<content>.*)!!! EOT \1 !!!/', $buffer, $matches);

// Build the stack
$stack = array_combine(array_values($matches['group']), array_values($matches['content']));

出力します:

Array
(
    [foo] => <p>Some HTML code</p>
    [bar] => <h1>Some other HTML code</h1>
)
于 2012-07-09T09:53:34.313 に答える
1

さて、ここに行きます。与えられた$template内容:

<!--- BEGIN foo -->
    <p>Some HTML code</p>
<!--- END foo -->

<!--- BEGIN bar -->
    <h1>Some other HTML code</h1>
<!--- END bar -->

それで:

$values = array();
$pattern = '#<!--- BEGIN (?P<key>\S+) -->(?P<value>.+?)<!--- END (?P=key) -->#si';
if ( preg_match_all($pattern, $template, $matches, PREG_SET_ORDER) ) {
    foreach ($matches as $match) {
        $values[$match['key']] = trim($match['value']);
    }
}
var_dump($values);

結果:

array(2) {
  ["foo"]=>
  string(21) "<p>Some HTML code</p>"
  ["bar"]=>
  string(29) "<h1>Some other HTML code</h1>"
}

空白の保持が重要な場合は、 を削除してtrim()ください。

于 2012-07-13T15:50:09.223 に答える