James
James

Reputation: 5169

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?

Upvotes: 0

Views: 2018

Answers (4)

filype
filype

Reputation: 8380

as others mentioned eval wouldn't be appropriate, I suggest a preg_replace or a preg_replace_callback if you need more flexibility.

preg_replace_callback('/\$(.+)/', function($m) {
     // initialise the data variable from your object  
     return $data[$m[1]];
}, $subject);

Check this link out as well, it suggests the use of strstr How replace variable in string with value in php?

Upvotes: 1

inhan
inhan

Reputation: 7470

Just an alternative.

$oEmails = new Emails('Me',4);
$str = 'sendingFrom=Sending emails from {$oEmails->agentName}, to {$oEmails->customerCount} people.';

// --------------

$arr = preg_split('~(\{.+?\})~',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
for ($i = 1; $i < count($arr); $i+=2) {
    $arr[$i] = eval('return '.substr($arr[$i],1,-1).';');
}
$str = implode('',$arr);
echo $str;
// sendingFrom=Sending emails from Me, to 4 people.

Upvotes: 2

ldiqual
ldiqual

Reputation: 15375

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).

Upvotes: 4

Toby Allen
Toby Allen

Reputation: 11213

You can use Eval with all the usual security caviats

Something like.

$string = getStringFromFile('sendingFrom');

$FilledIn = eval($string);

Upvotes: 0

Related Questions