Reproduce Smarty foreach with Php preg_match_all
-
22-08-2019 - |
Question
I would like to reproduce the "Smarty foreach" comportment.
The tpl file content is ($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}
The preg_match_all code is :
preg_match_all("/(.*)\{foreach(.*)\}(.*)\{\/foreach\}(.*)/im",$tplContent,$regsTplResult);
print_r($regsTplResult);
The print_r return :
Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
)
[3] => Array
(
)
[4] => Array
(
)
)
How i can return the code between {foreach}{/foreach} ?
Solution
I don't really understand what you're doing at all, but this seems to work:
$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);
OTHER TIPS
I found how to. The problem comes to \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);
The result is :
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."); }
)
)
The result that i want is in $regsTplResult[1][0]
Thank to "Chad Birch" ;)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow