开发者

Problem when calling a function in 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开发者_如何学JAVA'");
}

but as $id it understand $1, instead of 174 in query.

What is the reason? And how can i fix it?

Thanks much


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().


EDIT: if you are trying to replace it, you need to use preg_replace_callback() instead, like so:

$c = preg_replace_callback('/\[gallery=([0-9]+)\]/', 'gallery', $m);

function gallery($m)
{
   $id = (int) $m[1];
   $result = mysql_query("select * from `table` where `id` = '$id'");

   // Fetch $result and return the appropriate gallery code here
}

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:

$m = array();
preg_match('/\[gallery=([0-9]+)\]/', $content, $m);
$id = (int) $m[1]; // The value of the backreference $1
gallery($id);

Also I believe your gallery() function should return mysql_query() so you can analyze the result set of the query:

function gallery($id)
{
   return mysql_query("select * from `table` where `id` = '$id'");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜