【问题标题】:Reproduce Smarty foreach with Php preg_match_all使用 PHP preg_match_all 重现 Smarty foreach
【发布时间】:2009-04-02 18:54:07
【问题描述】:

我想重现“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} 之间返回代码?

【问题讨论】:

    标签: php foreach smarty preg-match-all


    【解决方案1】:

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

    $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);
    

    【讨论】:

    • 对不起,我的语法一定不好,我会在实际测试后一分钟编辑。
    • 对不起,没关系,但我认为这是我使用的真实内容造成了问题。我刷新我的问题。
    • 我认为问题出在空间和 cmets
    【解决方案2】:

    我找到了方法。问题来了 \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”;)

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多