Search code examples
phpstringvariablesvariable-variables

Parse variables within string


I'm storing some strings within a *.properties file. An example of a string is:

sendingFrom=Sending emails from {$oEmails->agentName}, to {$oEmails->customerCount} people.

My function takes the value from sendingFrom and then outputs that string on the page, however it doesn't automatically parse the {$oEmails->agentName} within. Is there a way, without manually parsing that, for me to get PHP to convert the variable from a string, into what it should be?


Solution

  • If you can modify your *.properties, here is a simple solution:

    # in file.properties
    sendingFrom = Sending emails from %s, to %s people.
    

    And then replacing %s with the correct values, using sprintf:

    // Get the sendingFrom value from file.properties to $sending_from, and:
    $full_string = sprintf($sending_from, $oEmails->agentName, $oEmails->customerCount);
    

    It allows you to separate the logic of your app (the variables, and how you get them) from your presentation (the actual string scheme, stored in file.properties).