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

Asked

Viewed 129 times

1

It is possible to walk a textarea to detect a text within the character [text] and turn it into a PHP function?

In short:

1. Scroll through a textarea

2. Find a text containing around []

3. Convert it to 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>
  • You want when detecting a content within a tag to execute the command?

  • Exactly. Edited.

  • Take the test to use jQuery $('textarea').html().replace('[galeria]', '<b>teste</b>') and very easy.

3 answers

2


To 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';
}
  • has a problem...where is the Lorem impsun? Just returns me "Gallery function". Have to return: Lorem impsun Functionlorem impsun gallery

  • I thought you only wanted what’s inside [] @Lollipop

  • No Manin :( can help? But I already gave +1 by preg_match

  • I will edit @Lollipop

  • Ediatdo @Lollipop

  • I love you...........

  • 1

    haha @Lollipop . Glad I could help

  • It’s cool the code, just one thing, because you use the /\[(.*?)\]/ twice? + 1

  • 1

    Obagdo is because it’s supposed to print what’s inside the <textarea> and replace the [...] by the return of the @zekk function. I also knew this only after the AP said in the first comment. I saw your answer, also would with str_replace after ... But do not forget that the functions may be more than one. There may be galeria1, galeria2 etc... That would be a lot of checks and the code would be extended. The last one is to replace where the text name of the function is

  • 1

    I understood what you meant... I created a var for Twitter @zekk. Obgado by repair

  • Miguel, creates a new one, below what he has already done, removing a preg_match, in the precise case that removes the condition so that it is NOT more between a <textarea>, but rather that it detects anywhere between [text]

  • That is any [...] right from any text @Lollipop

  • That. Imagine a lot of paragraph and between it there is a [func] that calls something. Forget the <textarea>, but keep the code above that show. It is the same idea will only take away the condition that limits between the textarea

  • The reason is because the other tags are disturbing the execution of the check and is giving error.

  • One question: There may be more than one [func]?

Show 11 more comments

2

You can also use the function strpos to check whether 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 like 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

See demonstração

  • And Lorem impsun? Why doesn’t he show up?

  • @Lollipop See the edition.

  • lol. perfect..

1

At @Lollipop’s request I did not edit/withdraw my first reply, and here I put an alternative solution that we concluded (by chat/comment conversation) 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 [...] this will remain in the text if you do not want to add else {...:

...
if(function_exists($func)) {
    ...
}
else {
    $final = str_replace('[' .$func. ']', '', $final);
}
...
  • PERFECT. No further comments.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.