Ale*_*lex 6 php string variables
所以字符串是这样的:
"bla bla bla {VARIABLE} bla bla"
Run Code Online (Sandbox Code Playgroud)
当我在函数中的某个地方使用这个字符串时,我想用$ variable(或任何其他包含在{} charcters中的大写字符串)替换{VARIABLE}.$ variable(和任何其他变量)将在该函数内定义
我能这样做吗?
Ale*_*sky 13
$TEST = 'one';
$THING = 'two';
$str = "this is {TEST} a {THING} to test";
$result = preg_replace('/\{([A-Z]+)\}/e', "$$1", $str);
Run Code Online (Sandbox Code Playgroud)
Bou*_*uke 13
使用正则表达式查找所有替换,然后迭代结果并替换它们.请务必仅允许您想要公开的变量.
// white list of variables
$allowed_variables = array("test", "variable", "not_POST", "not_GET",);
preg_match("#(\{([A-Z]+?)\}#", $text, $matches);
// not sure the result is in [1], do a var_dump
while($matches[1] as $variable) {
$variable = strtolower($variable);
// only allow white listed variables
if(!in_array($variable, $allowed_variables)) continue;
$text = str_replace("{".$match."}", $$match, $text);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8987 次 |
| 最近记录: |