php - 将单引号字符串转换为双引号 [英] php - convert single quoted string to double quoted
问题描述
在这里和谷歌搜索了一个多小时,似乎找不到答案.
Been searching here and google for over an hour, can't seem to find the answer to this.
我有一个从包含变量的数据库查询返回的字符串,但是这些字符串似乎都是单引号返回的,因此变量不会像双引号那样被评估.
I have a string returned from a database query which contains variables, however it appears that these strings are all returned single-quoted and therefore the variables are not evaluated as they would be if it was double quoted.
从 sql 查询返回的是 $result:
what is returned from the sql query would be the $result:
这不会评估 2 个变量:
This will not evaluate the 2 variables:
$myname = 'david';
$occupation = 'Beginner';
$result = 'Hello my name is $myname and I my occupation is $occupation';
echo $result;
这将评估 2 个变量:
This will evaluate the 2 variables:
$myname = 'david';
$occupation = 'Beginner';
$result = "Hello my name is $myname and I my occupation is $occupation";
echo $result;
我的问题是如何将单引号字符串转换为能够计算变量的双引号字符串??
My question is how do I convert a single-quoted string to a double-quoted string which is able to evaluate the variables ??
谢谢
推荐答案
PHP 目前没有标准的安全方法来执行此操作.多年来一直有一个开放的功能请求:http://bugs.php.net/bug.php?id=43901
PHP does not have a standard safe way to do this, right now. There has been an open feature request for years asking for it: http://bugs.php.net/bug.php?id=43901
票据上的一个评论提供了一个正则表达式来做简单的 $foo
和 ${foo}
替换:
One of the comments on the ticket offers a regex to do simple $foo
and ${foo}
substitution:
function stringExpand($subject, array $vars) {
foreach ($vars as $name => $value) {
$subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value, $subject);
}
return $subject;
}
这篇关于php - 将单引号字符串转换为双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!