如何在 PHP 中使用可变变量?
这就是我想要做的:
<?php
$my_str = "My String";
$str = "%my_str";
$str = str_replace("%", "$", $str);
echo $str;
?>
上面的代码将“$my_str”打印到屏幕上。但我希望它打印“我的字符串”,就像变量 $my_str 的实际值一样
有人知道如何做到这一点吗?
我想要这个的原因是因为我正在编写自己的非常基本的解析语言,所以我需要它发挥作用才能继续。
Here is what I am trying to do:
<?php
$my_str = "My String";
$str = "%my_str";
$str = str_replace("%", "$", $str);
echo $str;
?>
The above code prints '$my_str' to the screen. But I want it to print 'My String', as in the actual value of the variable $my_str
Anyone know how to do this?
The reason I want this is because I'm in the process of writing my own, very basic, parsing language so I kinda need this to be functional before I can continue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这种构造称为变量变量。
This construction is called a variable variable.
评估是没有必要的。只需去掉 % 并使用 $$str
eval is not necessary. Just get rid of the % and use $$str
您可以使用
preg_replace
和e
修饰符搜索并替换%var
模式,这使得替换被评估:这里
preg_replace< /code> 会找到
%my_str
,\1
包含my_str
和"$\\1"
(反斜杠需要转义)成为 $my_str 的值。但是,将替换字符串存储在关联数组中可能会更清晰:
You could search and replace the
%var
patterns usingpreg_replace
and thee
modifier, which makes the replacement being evaluated:Here
preg_replace
will find%my_str
,\1
containsmy_str
and"$\\1"
(the backslash needs to be escaped) becomes the value of $my_str.However, it would maybe be cleaner to store your replacement strings in an associative array:
尝试:
Try:
PHP 自动解析和扩展 double 内的变量- 带引号的字符串:
输出:
PHP automatically parses and expands variables within double-quoted strings:
Outputs:
如何使用带有 e 修饰符的正则表达式
(这是未经测试的,但应该可以工作)
How about using a regex with the e modifier
(This is untested, but should work)
您看到的行为并不奇怪 - 变量扩展(“插值”)仅在字符串文字上执行,而不是在变量上执行。如果不是,那么这将是一个很大的安全漏洞(您的代码使用的任何带有 $ 的字符串实例都会突然泄露变量)。
你可以尝试使用 eval 来修复这个问题,就像这样,
但这非常危险 - 如果你的字符串来自用户,那么可以使 $str 类似
,突然间,你就有麻烦了。我相信,最好的解决方案是使用您最喜欢的方法(stripos 和 substring 或其他方法)解析变量,然后手动替换每个变量。
The behaviour you see is not surprising - expansion of variables ("interpolation") is performed on only string literals, rather than variables. If it wasn't, then it would be a large security hole (any instance of a string with $ in it that your code used would suddenly be revealing variables).
You can try and fix this using eval, as in
but this pretty dangerous - if your string is from the user, then can make $str something like
and suddenly, you're in trouble. The best solution, I believe, will be to parse out variables using your favourite methods (stripos and substring, or something more), then replace each one by hand.