Substitution of variables in the body of the message

Asked

Viewed 233 times

6

I am creating a message profile system, when the system performs a certain action it picks up a certain profile and triggers the message as e-mail, however I would like in the body of the message, when written {{variavel}} I’d like him to take the value of $variavel corresponding (automatically), however I do not know what this method is called and I have not found any solution yet, will someone be able to give a little help?

Explanation:

I have the following message:

{{name}} Lorem Ipsum is Simply dummy text of the Printing and typesetting Industry {{email}}

To replace these values I would have to do as follows:

str_replace("{{nome}}", $nome, $mensagem);
str_replace("{{email}}", $email, $mensagem);

Only I wanted to do it in a way that was automatic.

  • For example: in the body of the message will contain this {{nome}} {{email}} I want this to be replaced by the variable that will be internally in PHP $nome $email with their respective values.

3 answers

3


After seeing the discussion, I arrived at the following solutions.

Could use the function preg_replace_callback.

function preg_parse($template, $vars) {
    $re = '/\{\{([^}]+)\}\}/';

    return preg_replace_callback($re, function($match) use($vars) {
        $key = trim($match[1]); //Remove os espaços da direita e esquerda do nome da variável
        return isset($vars[$key]) ? $vars[$key] : $match[0];
    }, $template);
}

Or automate setting variables in the @Sergio solution (from what I understood in the discussion was what was missing for you) .

function replace_parse($template, $vars) {
    $keys   = array_map(function($key) { return '{{'.$key.'}}'; }, array_keys($vars));
    $values = array_values($vars);

    return str_replace($keys, $values, $template);
}

Taking the example of the following code.

$vars     = array('nome' => 'foo', 'email' => '[email protected]');
$template = '{{nome}} Lorem Ipsum is simply dummy text of the printing and typesetting industry {{email}}';

echo preg_parse($template, $vars).PHP_EOL;
echo replace_parse($template, $vars).PHP_EOL;

The exit is.

foo Lorem Ipsum is simply dummy text of the printing and typesetting industry [email protected]
foo Lorem Ipsum is simply dummy text of the printing and typesetting industry [email protected]

But in function preg_parse removes spaces between tags {{ and }}, something that the replace_parse doesn’t make.

  • +1 for preg_replace_callback. Off: Still attending Fórum-Invaders? Luis/hacker_wap!

  • Eventually access, once a month +/- I take a peek there, you would be?

  • I was the Codersc. Good to see you here. =)

  • 1

    How long in, likewise.

  • The first example looks very interesting, I’ll give it a try. Thank you.

3

Another alternative that can be used is function strtr, it aims at, translate/replace certain characters of a string. Take an example:

$texto = 'Bem-vindo ao Stack Overflow em Inglês';
$traducao = array('Inglês' => 'Português');

echo strtr($texto, $traducao); // Bem-vindo ao Stack Overflow em Português

See demonstração

Assuming that the variables nome and email are already defined with the value you want, do the following:

$mensagem = '{{nome}} Lorem Ipsum is simply text of the printing and typesetting industry {{email}}';
$nome  = 'Maria';
$email = '[email protected]';

$traducao = array("{{nome}}"  => $nome, 
                  "{{email}}" => $email,
                 );

echo strtr($mensagem, $traducao);

See demonstração

1

To replace inside a string you can use the str_replace();.

The syntax is:

$stringFinal = str_replace("to replace", "substitute", "original string");

So in your case it could be something like

$email = str_replace({{variavel}}, $variavel, $corpoDoEmail);

You can also use arrays in str_replace. This way you can replace many pieces at a time:

$pedacos =     array('{{nome}}', '{{mail}}');
$substitutos = array($nome, $email);
$output  =     str_replace($pedacos , $substitutos , $corpoDoEmail);
  • this works, but if I have 100 variables I will have to do it for each of the 100. I wanted it to be automatic. I tried with the preg_replace() but I didn’t get any results.

  • @Italoizaac can explain better in question and join an example? 100 different variables in the text or make the substitution for 100 different texts?

  • @Italoizaac edited the answer.

  • I gave a small explanation in the original, take a look. Thanks in advance for trying to help!

  • @Italoizaac what do you mean "automatically"? doing this with arrays on str_replace is automatic tb...

  • But I would have to put each variable into the array ... automatically, without having to add another variable whenever I change one of it.

  • 1
Show 2 more comments

Browser other questions tagged

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