Retrieve PHP data within a text

Asked

Viewed 150 times

3

I have the following text::

$texto = "Olá {cliente}, seja bem vindo ao site {site}!
Aqui você terá acesso as seguintes opções:
{opcoes}

Estes dados foram gerados automaticamente em {data}
Pela empresa {empresa}";

Note that we have several tags between the keys, I need to draw up a PHP which retrieves only these tags, and places them within a array(), because I will include the tags in a differentiated table.

How could I retrieve only those inside the keys?

The result I would like would be:

Array (
      [0] => {x},
      [1] => {y}
)

2 answers

5


You can do it like this:

$texto = "Olá {cliente}, seja bem vindo ao site {site}!
Aqui você terá acesso as seguintes opções:
{opcoes}

Estes dados foram gerados automaticamente em {data}
Pela empresa {empresa}";

preg_match_all('/\{(.*?)\}/', $texto, $match);
print_r($match[0]); // Array ( [0] => {cliente} [1] => {site} [2] => {opcoes} [3] => {data} [4] => {empresa} )

It also works like this:

preg_match_all('#\{(.*?)\}#', $texto, $match);

Note that so each value of $match[0] has the included "{...}", if you do not want them you can access the Indice 1:

print_r($match[1]); // Array ( [0] => cliente [1] => site [2] => opcoes [3] => data [4] => empresa ) 
  • 5

    You were faster :P

  • Well that, perfect answer.

  • 1

    :) hehe Ussain preg_match @Inkeliz :P

  • @Andrébaill added another option with an alternative regular expression

  • Okay Miguel, tell me something... can I recover this data by a jquery? Example, I have a field called Description, normal input, as I type the texts, it will list these tags below?

  • This way you send the whole text to the server and are processing it with php, but could send the server only tags, IE, do this process in javascript and send only tags

  • In fact, I wanted to display, on the screen, what are the tags of the text that is being elaborated, or that it will paste inside the field... so that he knows the tags that will use.

Show 3 more comments

1

The Miguel replied very well the question, follows only another alternative using the functions strpos and substr:

function recuperarTags($texto){
    $inicio = 0;
    $tags = [];

    while (($inicio = strpos($texto, "{", $inicio)) !== false) {
        $final = strpos($texto, '}', $inicio + 1);
        $tamanho = $final - $inicio;
        $tag = substr($texto, $inicio + 1, $tamanho - 1);

        $tags[] = $tag;
        $inicio += 1;
    }
    return $tags;
}

To use, do so:

$texto = "Olá {cliente}, seja bem vindo ao site {site}!
Aqui você terá acesso as seguintes opções:
{opcoes}

Estes dados foram gerados automaticamente em {data}
Pela empresa {empresa}";

$tags = recuperarTags($texto);

foreach ($tags as $tag) {
    echo $tag ."\n";
}

See DEMO

Browser other questions tagged

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