English 中文(简体)
字符串内分析变量
原标题:Parse variables within string

我在 文件内存储一些字符串。 字符串的一个示例是 :

从 {$Emails- gt; aggt; agentName} / general> 发送来自 {$Emails- gt; 客户的电子邮件到 {$Emails- gt; customerCount} 的人 。

我的函数从 sending From 中取出该值,然后从页面上的输出字符串中取出该值, 但是它不会自动分析内部的 。 是否有一种方法, 无需手动解析, 就可以让 PHP 将变量从字符串转换为应该是什么?

最佳回答

如果您可以修改您的 , 下面是一个简单的解决方案 :

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

然后用正确值取代,使用sprintf :

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

它允许您从演示文稿( 保存在 < code> file. propertys 中的实际字符串方案) 中分离应用的逻辑( 变量, 以及如何获得变量) 。

问题回答

只是另一个选择而已

$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并不合适,我建议使用 preg_replace preg_replace_callback ,如果你需要更多灵活性的话。

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

也检查此链接, 它建议使用 strstrstr < a href=> "https://stackoverflow.com/ questions/ 150655387/ how- replace- evable- in- in- string- with- value- in- php" > 来替换字符串中的变量, 其值在 php 中?

您可以使用 Eval 使用所有常用的 安全带

类似的东西。

$string = getStringFromFile( sendingFrom );

$FilledIn = eval($string);




相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签