使用Php preg_match_all重现Smarty foreach

时间:2009-04-02 18:54:07

标签: php foreach smarty preg-match-all

我想重现“Smarty foreach”的比赛。

tpl文件内容是($ tplContent):

{foreach from=$tabMethodTest item=entry}
    /**
     * @todo Implement test{$entry.name}().
     */
    public function test{$entry.name}() {
        $this->markTestIncomplete("This test has not been implemented yet.");
    }
{/foreach}

preg_match_all代码是:

preg_match_all("/(.*)\{foreach(.*)\}(.*)\{\/foreach\}(.*)/im",$tplContent,$regsTplResult);
print_r($regsTplResult);

print_r返回:

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

    [3] => Array
        (
        )

    [4] => Array
        (
        )

)

我如何在{foreach} {/ foreach}之间返回代码?

2 个答案:

答案 0 :(得分:0)

我真的不明白你在做什么,但这似乎有效:

$tplContent = "{foreach from=\$tabMethodTest item=entry}\nHello\n{/foreach}";
$pattern = '/\{foreach from=\$tabMethodTest item=entry\}[\r\n]{1,2}(.*)[\r\n]{1,2}\{\/foreach\}/im';
preg_match_all($pattern,$tplContent,$regsTplResult);
print_r($regsTplResult);

答案 1 :(得分:0)

我找到了怎么样。问题来自\ r \ n:

$pattern = '/\{foreach from=\$tabMethodTest item=entry\}(.*)\{\/foreach\}/im';
$tplContent = preg_replace("/[\n\r]/","",$tplClassTestContent);
preg_match_all($pattern,$tplContent,$regsTplResult);
print_r($regsTplResult);

结果是:

Array
(
    [0] => Array
        (
            [0] => {foreach from=$tabMethodTest item=entry} /**     * @todo Implement test{$entry.name}().     */    public function test{$entry.name}() {        $this->markTestIncomplete("This test has not been implemented yet.");    }    {/foreach}
        )

    [1] => Array
        (
            [0] =>  /**     * @todo Implement test{$entry.name}().     */    public function test{$entry.name}() {        $this->markTestIncomplete("This test has not been implemented yet.");    }    
        )

)

我想要的结果是$ regsTplResult [1] [0]

感谢“Chad Birch”;)