PHP 函数和变量以字符串形式存储在数据库中

标签 php string function eval

我需要将数据存储在数据库中,当我从数据库获取数据时,我需要字符串中的函数和变量进行计算。

示例

$str = "<p>Dear {$this->name},</p>"

然后我将其存储在数据库中,当我检索字符串并运行它时

eval("\$detail= \"$detail\";");

然后变量将被填充名称。这正是我所需要的并且工作正常。

问题是我想运行一个以此变量作为参数的函数。

示例。我想要 ucwords 变量。

我已经尝试过:

$str = "<p>Dear {ucwords($this->name)},</p>"  //just echoed {ucword(->name)},
$str = "<p>Dear {ucwords($this->name)},</p>"  //Fatal error: Function name must be a string,

我的方向正确吗? 这有可能吗?

最佳答案

您不需要将 PHP 代码保存在数据库中。这是一种不好的做法,也可能导致安全漏洞。

而是像这样存储在数据库字符串中:

<p>Dear [name],</p>

当你检索它时,你可以这样做:

$stringFromDb = str_replace("[name]", $this->name, $stringFromDb);

$stringFromDb = str_replace("[name]", ucwords($this->name), $stringFromDb);

其他常见方法是使用sprintf。因此,您需要将 %s 作为值的占位符存储在数据库字符串中。

示例:

<p>Dear %s,</p>

并替换为

$stringFromDb = sprintf($stringFromDb, ucwords($this->name));

关于PHP 函数和变量以字符串形式存储在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14237891/

相关文章:

r - 根据部分字符串或子字符串更改列名称

php - 如何调用常量作为函数名?

c++ - "Error: function does not take 4 arguments"但确实如此

php - 使用 array_multisort() 并将空值放在最后,而不是放在前面

php - 获取 $_FILES 数组的键

string - 在 Rust 中将 Vec<String> 转换为 &str 的一部分?

javascript - Javascript 字符串中每个单词的首字母大写

function - Mapcat 是如何工作的?

php - Python:CGI程序想知道调用网页的IP地址

php - Wordpress 为前端主题 functions.php 包含 jQuery UI Checkboxradio