<?php
function funcao1() {
return '<Funcao galeria 1>';
}
function funcao2() {
return '<Funcao galeria 2>';
}
function extrairPalavras($texto, $sepInicial, $sepFinal){
$resultado = [];
$contador = $inicio = $final = 0;
while ($contador < strlen($texto)){ $posIn = strpos($texto, $sepInicial, $inicio); $posFn = strpos($texto, $sepFinal, $final);
if ($posIn !== false){
$inicio = $posIn + 1;
if ($posFn !== false){
$final = $posFn + 1;
$resultado[$inicio] = $final;
}
}
$contador++;
}
return $resultado;
}
$texto = "Lorem [funcao2] impsun [funcao1] Lorem [heya] impsun";
$indices = extrairPalavras($texto, '[', ']');
foreach($indices as $inicial => $final){
$nomeFunc = substr($texto, $inicial, $final - $inicial - 1);
if (!isset($textoResultado)){ $textoResultado = str_replace("[$nomeFunc]", $nomeFunc(), $texto); continue;
}
$textoResultado = str_replace("[$nomeFunc]", $nomeFunc(), $textoResultado); }
}
echo $textoResultado . "\n";
PD9waHAKCmZ1bmN0aW9uIGZ1bmNhbzEoKSB7CiAgICByZXR1cm4gJzxGdW5jYW8gZ2FsZXJpYSAxPic7Cn0KZnVuY3Rpb24gZnVuY2FvMigpIHsKICAgIHJldHVybiAnPEZ1bmNhbyBnYWxlcmlhIDI+JzsKfQoKZnVuY3Rpb24gZXh0cmFpclBhbGF2cmFzKCR0ZXh0bywgJHNlcEluaWNpYWwsICRzZXBGaW5hbCl7CgkkcmVzdWx0YWRvID0gW107CgkkY29udGFkb3IgPSAkaW5pY2lvID0gJGZpbmFsID0gMDsKCgl3aGlsZSAoJGNvbnRhZG9yIDwgc3RybGVuKCR0ZXh0bykpewoJCSRwb3NJbiA9IHN0cnBvcygkdGV4dG8sICRzZXBJbmljaWFsLCAkaW5pY2lvKTsKCQkkcG9zRm4gPSBzdHJwb3MoJHRleHRvLCAkc2VwRmluYWwsICRmaW5hbCk7CgoJCWlmICgkcG9zSW4gIT09IGZhbHNlKXsKCQkJJGluaWNpbyA9ICRwb3NJbiArIDE7CgkJCQoJCQlpZiAoJHBvc0ZuICE9P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