0

Seeing how eval should be avoided, how do you evaluate a string as PHP code without using eval? For example consider this code:

<?php

$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.'; 

$str = "\"$str\""; // Now I have a string with double quotes around it. 

// how to get the contents of $str evaluated without using eval()

?>

I can get the desired result by using eval like so - eval("echo $str;");, but eval is exactly what I am looking to avoid.

You might view this as a question of removing the double quotes. But it isn't about that. As @AmalMurali points out, what I am asking here is how to get the contents of $str evaluated without using eval()

user1720897
  • 1,216
  • 3
  • 12
  • 27

3 Answers3

2

You can layout your code like this:

$string = 'cup';
$name = 'coffee';
$str = 'This is a ' . $string . ' with my ' . $name . ' in it.'; 

Or perhaps like this, using sprintf which is my personal favorite method of handling cases like this:

$string = 'cup';
$name = 'coffee';
$str = sprintf('This is a %s with my %s in it.', $string, $name); 

There are different options based on personal style & preference.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
1

What you really want here is to use double quotes for $str so that variable replacement can take place.

See also the docs: http://www.php.net/manual/it/language.types.string.php#language.types.string.syntax.double

Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
1

Why are you adding double quotes then removing them? For a simple string variable inclusion you just use double quotes like

$string = 'cup';
$name = 'coffee';
$str = "This is a $string with my $name in it."; 

echo $str;
WebChemist
  • 4,393
  • 6
  • 28
  • 37