"Variable system" with regular expressions

7

I have a file something like this:

%usuario: 'Anônimo'
Olá <b>%{usuario}</b>

(This is just an example and is not the real case), but I think if I were to explain the real problem it would give me a lot more work to understand, so it's this: I'm lousy in regular expressions and I have to display this file replacing the variables that will always be in this model:

%var_name = valor;

And display them when they are requested, like this: %{var_name}

    
asked by anonymous 11.04.2014 / 16:46

2 answers

6

Recommended solution without regex:

The following example merges two texts, one with the variables and the other with the templates. I think it's pretty easy to adapt for your use:

<?php

   $variaveis = <<<DELIMITADOR
      usuario: chico
      mensagens: 17
DELIMITADOR;

   $texto = <<<DELIMITADOR
      Ola %{usuario}, voce tem %{mensagens} mensagens!
DELIMITADOR;

   $linhas = explode(chr(10), $variaveis); // divite o texto em array, pela quebra de linha
   foreach ($linhas as $linha) {
      $partes = explode(':',$linha);       // divide cada linha em 2 partes, pelos ":"
      $variavel = trim($partes[0]);        // Remove os espaços em branco
      $valor= trim($partes[1]);            // Remove os espaços em branco
      // Agora, basta fazer a troca da %{variavel} pelo valor:
      $texto = str_replace('%{'.$variavel.'}',$valor, $texto);
   }

   echo htmlentities($texto);

?>

Result:

Ola chico, voce tem 17 mensagens!

Just adapt the variable and text declarations to your case, or simply read both from external files.

  

Even if everything is in one file, just use the same principle of foreach and explode to separate the file in several lines, and split the part of the variables of the part of the template itself (for example, checking if the line starts with % ).

    
11.04.2014 / 17:02
3

Depending on the requirements (since it was mentioned that the question is a simplified example), the goal of replacing variables and generating content based on a template from outside the program can be achieved with a template engine.

Advantages

Do not reinvent the wheel

It is better to reap the hard work of other developers than to implement something like this "from scratch". You avoid spending time on your own and avoid many mistakes and mishaps.

More resources (formatting, listing, variables)

At first it may be necessary to only replace one or two fields. But what to do when the entry contains, say a list of items? What about formatting dates?

The advantage of using a generic template engine is that it already comes "to toast" with these features,

Disadvantages

Memory and Storage

Using a template engine will probably add more files and classes than a simpler own solution.

Performance

Depending on the features needed, a template engine might be less efficient, as it has many unused features. However, depending on the amount of replacement operations performed, this may change.

Examples of template engines

Blitz

Sample code:

$View = new Blitz();
$View->load('hello {{ BEGIN block }} {{ $name }} {{ END block }}');
$View->block('/block', array('name' => 'Dude'));
$View->display();

Produce:

  

"hello Dude"

phpTenjin

Template:

Hello {==$name=}!

The template is converted to PHP:

<?php echo 'Hello ', $name, '!'; ?>

The execution can be done like this:

require_once 'Tenjin.php';
$engine = new Tenjin_Engine();
$context = array('name'=>'World');
$output = $engine->render('ex.phtml', $context);
echo($output);

Output:

  

Hello World!

eZ Components - Template

Code to run:

// Autoload classes ezcomponent 
function __autoload( $className ) {
    ezcBase::autoload( $className );
}

//cria engine com configuração padrão
$t = new ezcTemplate();

//passar variável para o template
$t->send->a = 1;

// compila o template e imprime a saída
echo $t->process( "hello_world.ezt" );

Template:

{use $a, $b = 2}
{$a}, {$b}

Output:

  

1, 2

Dwoo

Template:

Hello {$name}

Code to run:

require 'lib/Dwoo/Autoloader.php';
\Dwoo\Autoloader::register();

$dwoo = new \Dwoo\Core();
$data = array('name'=>'World');
$dwoo->output('caminho/template.tpl', $data);
    
11.04.2014 / 17:42