0
$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

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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'");
}

1 Comment

But i need to replace it. if i have a text in$content before and after [gallery=174], i need to store them, just replcace the [...] with some content (returned from database)...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.