Воспроизвести Smarty foreach с помощью Php preg_match_all
-
22-08-2019 - |
Вопрос
Я хотел бы воспроизвести поведение "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} ?
Решение
Я вообще не совсем понимаю, что вы делаете, но, похоже, это работает:
$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);
Другие советы
Я нашел, как это сделать.Проблема сводится к :
$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]
Спасибо "Чаду Берчу" ;)
Не связан с StackOverflow