"Variable system" with regular expressions

Asked

Viewed 402 times

7

I have a file like this:

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

(This is just an example and this is not the real case), but I believe that if I were to explain the real problem it would be much more work to understand, then it is the following: I am bad at 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’re requested, that way: %{var_name}

  • I do not understand what is the final outcome you want to reach. You can explain more in the question?

  • If I declare a variable age with value of 17, and in the file there is 'I am %{age} years old' the output would be 'I am 17 years old' understood? (I can’t edit the file because it’s off my server)

  • What exactly can you have in value ? It seems to me that you will have to create some kind of minilanguage to handle strings/numbers. A eval wouldn’t be nice since the file isn’t on your server..

  • 2

    you are mounting a template system?

  • 2

    Not for nothing, but regex is the last thing to use in a case like this.

  • Yeah, it’s more or less a template system. @Bacco I was thinking of using regex to return the variable name and its value, and use to replace them in the files, but if you have a better method feel free to share it.

  • @Junior posted a very didactic solution so that it is easy to take advantage and adapt as used. Regex would kill pigeon with cannon shot.

Show 2 more comments

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 is very 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);

?>

Upshot:

Ola chico, voce tem 17 mensagens!

Simply adapt the statements of variables and text to your case, or simply read both from external files.

Even if it’s all in one file, just use the same principle of foreach and of explode to separate the file into several lines, and split the variable part of the template itself (for example, by checking whether the line starts with %).

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 model from outside the program can be achieved with a template engine.

Perks

Don’t reinvent the wheel

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

More resources (formatting, listing, variables)

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

The advantage of using a template engine generic is that it already comes "free" with these resources, and other.


Disadvantages

Memory and storage

Use a template engine will likely aggregate more files and classes than a simpler solution of its own.

Performance

Depending on the necessary resources, a template engine can be less efficient as it has many unused resources. However, depending on the amount of replacement operations performed, this the framework can 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();

Produces:

"hello Dude "

phpTenjin

Template:

Hello {==$name=}!

The template is converted to PHP:

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

The execution can be done so:

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

Exit:

Hello World!

Ez Components - Template

Code for implementation:

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

Exit:

1, 2

Dwoo

Template:

Hello {$name}

Code for implementation:

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

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

Browser other questions tagged

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