Using preg_replace with a function

Hey, I am trying to write a sort of replace function where [tt]{user:1}[/tt] is converted into a set of information from a database using preg_replace. So I have created the following preg_replace:

[php]$patterns = array();
$patterns[1] = ‘/{user:([0-9]+)}/’;

$replacements = array();
$replacements[1] = UserCredit(’$1’);


$content_show = preg_replace($patterns, $replacements, $content);

echo $content_show;

and then the function UserCredit which is just above that on the page:

[php]function UserCredit($user_id) {
require ‘connect.php’;
$user_lookup = mysql_query(“SELECT * FROM prop_users WHERE ID = ‘$user_id’”);
while($row = mysql_fetch_array($user_lookup)) {
$user_name = $row[‘full_name’];
$user_file = $row[‘credit_file’];
$user_url = $row[‘link_url’];
$user_url_alt = $row[‘link_alt’];
die(“An error has occured, Sorry for any Inconvenience Caused! User ID=”.$user_id);
require ‘close.php’;
$output = “<li class=“clearfix”><div class=“credimg”><img src=”".$user_file."" width=“75px” height=“75px” alt="".$user_name."" />

<a href="".$user_url."" title="".$user_url_alt."">".$user_name.“
Writing / Code

return $output;

I have tested the function and it works when I echo UserCredit(‘1’);

And the preg_replace works at simply extracting the value for the user.

The only problem is that I can’t figure a way for the preg_replace to carry the value of $1 into the function it just literally carries “$1”

Is there something obvious that I am missing or am I going around this the wrong way?

Since your function UserCredit() returns string for certain $user_id, you need first to determine this id in the source string. I would suggest to use preg_match() or preg_match_all() and then within a loop (if there are more than one id found) you would call your function UserCredit() for each id, and replace with preg_replace().

Also, I noticed you’re including connect.php and close.php within a function. This is not good, as this will be included every time when you call this function. If these two included files are to connect to a MySQL database and close the connection - you can do this once in the script, outside the function.

I have fixed the includes to the files like you suggested.

Although I’m not sure I understand your solution for the preg_replace.

The string $content which I am replacing the values in is a large chunk of text from a MySQL database. I would like the preg_replace to then search for every {user:x}
I don’t understand which source string you are referring to.

Thanks for the Help

Nevermind, found to solution.

[php]$patterns[1] = ‘/{user:([0-9]+)}/e’;

$replacements[1] = ‘UserCredit("$1")’;[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service