Reproducirse foreach Smarty con PHP preg_match_all
-
22-08-2019 - |
Pregunta
Me gustaría reproducir el comportamiento "Smarty foreach".
El contenido del archivo TPL es ($ 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}
El código preg_match_all es:
preg_match_all("/(.*)\{foreach(.*)\}(.*)\{\/foreach\}(.*)/im",$tplContent,$regsTplResult);
print_r($regsTplResult);
El retorno print_r:
Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
)
[3] => Array
(
)
[4] => Array
(
)
)
¿Cómo puedo devolver el código entre {} {foreach / foreach}?
Solución
No entiendo muy bien lo que está haciendo en absoluto, pero esto parece que funciona:
$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);
Otros consejos
He encontrado cómo. El problema viene a \ 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);
El resultado es:
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."); }
)
)
El resultado es que quiero en $ regsTplResult [1] [0]
Gracias a "Chad abedul";)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow