0

I was wondering if there was a way to have an automatic variable replacement inside a string. I can simulate this right now with preg_replace and strtr but am not sure if there's a better way. I was thinking of using eval, but can't seem to figure out how to do it properly.

strtr

<?php
    $replacement = array('$test' => "dog");
    $template = 'this is a $test';
    $statement = strtr($template, $replacement);
    echo $statement;
?>

preg_replace

<?php
    $template = 'this is a $test';
    $statement = preg_replace('/\$test/', 'dog', $template);
    echo $statement;
?>

eval idea

<?php
    $template = 'this is a $test';
    $test = 'dog';
    eval('$statement = "$template";');
    echo $statement;
?>
5
  • You need to be very, very, very, very careful to validate your string to the highest degree before using eval(). eval() may make hacking your site much simpler for clever, naughty people. It is not against the law to use eval() but it is often strenuously discouraged due to vulnerabilities. I would urge you to make eval() your plan Z -- only to be used when everything else fails to perform as you require. Commented Jul 17, 2017 at 1:35
  • Are the other two functions failing you in any specific situations? They seem like a wiser choice for this task. Commented Jul 17, 2017 at 1:46
  • @mickmackusa I'm thinking it's going to be faster, not sure. eval should be safe since they'll be variables I'm defining myself. Not user/client side input. Commented Jul 17, 2017 at 1:52
  • Is speed a valid concern for your project? or are you micro-optimizing? Commented Jul 17, 2017 at 1:54
  • @mickmackusa ah, not speed as in optimising, speed as in I have to type less. Idk, haven't really thought it out too much lol. I forget the syntax of preg_replace and what not often. Commented Jul 17, 2017 at 1:54

1 Answer 1

1

eval() is to evalute a string as if it's PHP code. So if you did:

<?php

$template = 'this is a $test';
$test = 'dog';

eval($template);
echo $template;

?>

You would get a syntax error:

Parse error: syntax error, unexpected 'is' (T_STRING)

Because you would in fact do this:

<?php

$template = 'this is a $test';
$test = 'dog';

this is a $test;

echo $template;

?>

So instead, you need to evaluate it as a string in double quotes so the variable gets replaced by its value:

<?php

$template = 'this is a $test';
$test = 'dog';

eval("\$template = \"$template\";");

echo $template;

?>

Which would be something like this:

<?php

$template = 'this is a $test';
$test = 'dog';

$template = "this is a $test";

echo $template;

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.