如何在 PHP 中实现类似 printf 的函数?
我想为我的数据库抽象创建一个 db_queryf 函数。它的工作方式有点像 SQLite 中的 sqlite3_mprintf
:db_queryf('select * from pages where name=%q', $_GET['name'])
,其中 %q 将生成正确转义的字符串。在 PHP 中创建类似 printf 的函数的正确方法是什么?是否有任何辅助函数,或者我应该自己解析它?
I want to make a db_queryf
function for my database abstraction. It will work somewhat like sqlite3_mprintf
from SQLite: db_queryf('select * from pages where name=%q', $_GET['name'])
, where %q will produce a properly escaped string. What is the proper way of making printf-like functions in PHP? Is there any helper functions for that or I should parse it myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我很困惑...
(s)printf
显然已经存在,并且您可能想使用SQLite3Stmt::bindValue
更多信息,除非你想最终陷入逃避/sql注入地狱。I am confused...
(s)printf
plainly allready exists, and you probably want to useSQLite3Stmt::bindValue
more for this, unless you want to end up in escaping / sql-injection hell..使用PDO 准备好的语句。替换为字符串还不够好,您应该进行清理。
Use PDO prepared statements. Replacing into the string isn't good enough, you should be sanitizing.
sprintf()
清理所有内容非常很重要在使用之前,在
$_GET
中!sprintf()
Its very important, that you sanitize everything in
$_GET
, before you use it!好吧,由于我遇到了完全相同的问题,所以我尝试了一下,看起来效果很好。
以下函数位于数据库包装类中,并期望像 printf 一样被调用,其中
%%
被转换为文字 %,%e
将字符串参数标记为转义,并且%u
标记要按原样获取的字符串参数。LOGDB 是第二个数据库包装类,负责捕获和记录各种错误。
注意:代码大部分未经测试,很可能包含一堆错误。谨慎使用:)
okay, since I had exactly the same problem, I gave it a shot, and it seems to work quite nicely.
The following function sits inside a database wrapping class, and expects to be called like printf, where
%%
is transformed to a literal %,%e
marks a string argument to be escaped, and%u
marks a string argument to taken as-is.LOGDB
is a second database wrapping class, that is responsible for catching and logging all kinds of errors.Note: the code is mostly untested, chances are, it contains a bunch of bugs. use with caution :)