Detect text inside a special character and convert it into a PHP function

1

You can go through a textarea to detect a text within the [text] character and transform it into a PHP ?

Summarizing:

1. Go through a textarea

2. Find a text containing around []

3. Converts it into a php function

4. Example: [text] = Abrephp text (); Fechaphp

In practice:

 ...

  <textarea>Lorem impsun [galeria] Lorem impsun</textarea>

 ....

 //Então ao ler a informação "Lorem impsun [galeria] Lorem impsun"
 //O escopo irá tratar como(não dinamicamente):

 ...

 <div>Lorem impsun <?php galeria(); ?> Lorem impsun<div>
    
asked by anonymous 03.08.2016 / 16:30

3 answers

2

For the example you gave:

function galeria() {
    return 'Funcao galeria';
}
preg_match('/<textarea>(.*?)<\/textarea>/', '<textarea>Lorem impsun [galeria] Lorem impsun</textarea>', $matches1);
$funcPattern = '/\[(.*?)\]/';
preg_match($funcPattern, $matches1[1], $matches2);
if(isset($matches2[1])) {
    if(function_exists($matches2[1])) {
        echo preg_replace($funcPattern, $matches2[1](), $matches1[1]);
    }
    else {
        echo 'Função ' .$matches2[1]. '() não existe';
    }
}
else {
    echo 'não há função definida';
}
    
03.08.2016 / 16:41
2

You can also use the strpos function to check if a string is found in a text.

<form method="post" action="#">
  <textarea name="texto" rows="4" cols="40">Lorem impsun [galeria] Lorem impsun</textarea>
  <input type="submit" name="submit" value="Enviar" id="submit"/>
</form>

<?php

$valorTextarea = isset($_POST['texto']) ? $_POST['texto'] : "";

if (strpos($valorTextarea, "[galeria]") !== false){
    FuncaoGaleria();
} else {
    echo "Palavra-chave não encontrada!\n";
}

function FuncaoGaleria(){
    echo "Função Galeria!\n";
}

?>

Editing

To extract more than one keyword from the text, use the following function:

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;
}

Use this:

function funcao1() {
    return '<Funcao galeria 1>';
}
function funcao2() {
    return '<Funcao galeria 2>';
}

$texto = "Lorem [funcao2] impsun [funcao1] Lorem [heya] impsun";
$indices = extrairPalavras($texto, '[', ']');

foreach($indices as $inicial => $final){
    $nomeFunc = substr($texto, $inicial, $final - $inicial - 1);

    if(function_exists($nomeFunc)) {
        if (!isset($textoResultado)){
            $textoResultado = str_replace("[$nomeFunc]", $nomeFunc(), $texto);
            continue;
        }
        $textoResultado = str_replace("[$nomeFunc]", $nomeFunc(), $textoResultado);  
    }
}
echo $textoResultado . "\n";
// Lorem <Funcao galeria 2> impsun <Funcao galeria 1> Lorem [heya] impsun

View demonstração

    
03.08.2016 / 18:56
1

At the request of @Lollipop I did not edit / remove my first answer, and I put here a workaround that we concluded (by conversation in comments / chat) that would be better:

function galeria1() {
    return htmlentities('<Funcao galeria 1>');
}
function galeria2() {
    return htmlentities('<Funcao galeria 2>');
}
$texto = 'Lorem [galeria2] impsun [galeria1] Lorem [heya] impsun';
preg_match_all('/\[(.*?)\]/', $texto, $matches);
foreach($matches[1] as $func) {
    if(function_exists($func)) {
        if(!isset($final)) {
            $final = str_replace('[' .$func. ']', $func(), $texto);
            continue;
        }
        $final = str_replace('[' .$func. ']', $func(), $final);
    }
}
echo $final;

If there is an undeclared function within [...] it will remain in the text, if you do not want to add else {... in the text:

...
if(function_exists($func)) {
    ...
}
else {
    $final = str_replace('[' .$func. ']', '', $final);
}
...
    
03.08.2016 / 21:56