0

Is there a way to evaluate an expression right inside of a PHP string?

In Perl you can do a trick with creating a reference to an array and then dereferencing it right away. When Perl interpolates the string it will compute the expression inside the array reference:

"string @{[2+2]} string"

and it will evaluate 2+2 inside of a string.

What about PHP. Is there such construct in PHP that lets you evaluate expressions inside of a string (through interpolation)?

bodacydo
  • 75,521
  • 93
  • 229
  • 319
  • possible duplicate of [How to evaluate formula passed as string in PHP?](http://stackoverflow.com/questions/1015242/how-to-evaluate-formula-passed-as-string-in-php) –  Oct 23 '14 at 03:46
  • 1
    No, but you can use something like this - https://github.com/jlawrence11/Classes + http://stackoverflow.com/questions/5057320/php-function-to-evaluate-string-like-2-1-as-arithmetic-2-1-1 – Cheery Oct 23 '14 at 03:48
  • Is the expression hard-coded in the string like that, or are you being passed a string that contains the expression and you need to evaluate it? If it's hard-coded, just take it out and concatenate, like Jonathan Gray's answer. – Barmar Oct 23 '14 at 03:48
  • 1
    @Dagon Based on that possible dupe link, OP may as well stick with PERL. – Funk Forty Niner Oct 23 '14 at 03:49
  • Either `preg_replace_callback` (the `/e` approach was simpler and permissible for such narrow patterns), or string varexpressions with `$_ = "trim";` and `echo "string {$_(2+2)} string";` for instance. – mario Oct 23 '14 at 03:54
  • 1
    The simple answer is: **No**. PHP does not evaluate expressions inside strings. – Sverri M. Olsen Oct 23 '14 at 04:01
  • The less simple answer is: **YES**. PHP can evaluate expressions through callback-functions, see post below. – Teson May 19 '15 at 09:06

2 Answers2

0
$x = "string ".(2+2)." string";
Darren
  • 13,050
  • 4
  • 41
  • 79
Jonathan Gray
  • 2,509
  • 15
  • 20
  • Well it gets the job done. PHP is an interpreted language, but is also compiled to bytecode for performance improvements. It doesn't matter exactly how you accomplish the task because either way the engine will know you want a string plus the result of an equation plus another string as the final string output. – Jonathan Gray Oct 23 '14 at 03:53
  • I think this is the best answer. Unless someone has a smarter answer, I will be accepting this answer. – bodacydo Oct 23 '14 at 22:46
0

Looking for the same, I did the following, and you could even simulate that perl-syntax:

    $s = 'testing to calculate @{[sin(2+2)]} and @{[round(cos(23*3),3)]}';
    $s = preg_replace_callback("[@{\[(.*?)\]\}]",'parseEval',$s);
    echo $s;
    //output: testing to calculate -0.75680249530793 and 0.993

    function parseEval($match) {
      //unsecure but still..
      eval('$ev = ' . $match[1] . ';');
      return $ev;
    }
Teson
  • 6,644
  • 8
  • 46
  • 69