在 preg_replace 中调用函数时出现问题
$content = "... [gallery=174] ... ";
echo $c = preg_replace('/\[gallery=([0-9]+)\]/',gallery("$1"),$content);
function gallery($id)
{
mysql_query("select * from `table` where `id` = '$id'");
}
但作为 $id
它理解 $1
,而不是查询中的 174
。
原因是什么?我该如何解决它?
非常感谢
$content = "... [gallery=174] ... ";
echo $c = preg_replace('/\[gallery=([0-9]+)\]/',gallery("$1"),$content);
function gallery($id)
{
mysql_query("select * from `table` where `id` = '$id'");
}
but as $id
it understand $1
, instead of 174
in query.
What is the reason? And how can i fix it?
Thanks much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
preg_replace
无法实现您想要执行的操作:gallery()
将在搜索字符串之前执行,您无法指定$1
结果是其参数。您正在寻找
preg_replace_callback()
。What you are trying to do is not possible using
preg_replace
:gallery()
will be executed before the string is searched, you can't specify the$1
result in its parameters.You are looking for
preg_replace_callback()
.编辑:如果您尝试替换它,则需要使用
preg_replace_callback()
,如下所示:旧答案
您应该使用
preg_match()
来查找匹配项,因为您并不尝试将其替换为 SQL 查询,而只是从字符串中获取要在 SQL 查询中使用的值。试试这个:我还相信你的gallery()函数应该返回mysql_query(),这样你就可以分析查询的结果集:
EDIT: if you are trying to replace it, you need to use
preg_replace_callback()
instead, like so:Old answer
You should use
preg_match()
to find the match because you're not trying to replace it with an SQL query, simply obtaining the value from the string to use in the SQL query. Try this:Also I believe your
gallery()
function should returnmysql_query()
so you can analyze the result set of the query: