Expanding variables within a string?

Discussion in 'PHP' started by Lauxa, Nov 28, 2007.

  1. #1
    Is it possible to expand variables within a string? For example:

    $var = grape;
    $str1 = 'The item is a $var';

    Now do some operation on $str1, so that the output turns out to be:

    The item is a grape

    I am not talking about putting double quotes around the string when it is set or doing some sort of search/replace on a specific variable name. I would like to know if there is a way to get ALL the variables within a string to evaluate after the string is already set.

    ~Lauxa
     
    Lauxa, Nov 28, 2007 IP
  2. mvl

    mvl Peon

    Messages:
    147
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
        $str='The item is a $var';
        $var="grape";
        eval("\$str=\"$str\";");
        echo $str;
    
    Code (markup):
     
    mvl, Nov 28, 2007 IP
  3. Lauxa

    Lauxa Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Awesome, thanks a ton!
     
    Lauxa, Nov 28, 2007 IP
  4. vonvhen

    vonvhen Peon

    Messages:
    152
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    also this will work and easier to do

    $var="grape";

    $str="The item is a ".$var;
     
    vonvhen, Nov 28, 2007 IP
  5. mvl

    mvl Peon

    Messages:
    147
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #5
    This will not work. Lauxa asked for a solution where you first assign $str and then $var, not $var first and then $str.
     
    mvl, Nov 29, 2007 IP
  6. Elad-A

    Elad-A Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Examples: http://php.net/eval
     
    Elad-A, Nov 29, 2007 IP