我在*.properties
文件中存储了一些字符串。一个字符串的例子是:
sendFrom=从 {$oEmails->agentName}向 {$oEmails->customerCount} 人发送电子邮件。
我的函数从中获取值sendingFrom
,然后在页面上输出该字符串,但是它不会自动解析其中的{$oEmails->agentName}
内容。有没有办法让我在不手动解析的情况下让 PHP 将变量从字符串转换为应有的值?
我在*.properties
文件中存储了一些字符串。一个字符串的例子是:
sendFrom=从 {$oEmails->agentName}向 {$oEmails->customerCount} 人发送电子邮件。
我的函数从中获取值sendingFrom
,然后在页面上输出该字符串,但是它不会自动解析其中的{$oEmails->agentName}
内容。有没有办法让我在不手动解析的情况下让 PHP 将变量从字符串转换为应有的值?
如果你可以修改你的*.properties
,这里是一个简单的解决方案:
# in file.properties
sendingFrom = Sending emails from %s, to %s people.
然后使用sprintf%s
替换为正确的值:
// Get the sendingFrom value from file.properties to $sending_from, and:
$full_string = sprintf($sending_from, $oEmails->agentName, $oEmails->customerCount);
它允许您将应用程序的逻辑(变量以及获取它们的方式)与演示文稿(实际的字符串方案,存储在 中file.properties
)分开。
只是一种选择。
$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.
正如其他人提到的那样, eval 不合适,如果您需要更大的灵活性,我建议 apreg_replace
或 a 。preg_replace_callback
preg_replace_callback('/\$(.+)/', function($m) {
// initialise the data variable from your object
return $data[$m[1]];
}, $subject);
也检查这个链接,它建议使用strstr
How replace variable in string with value in php?
您可以将 Eval 与所有常见的安全漏洞一起使用
就像是。
$string = getStringFromFile('sendingFrom');
$FilledIn = eval($string);