Why do you need regular expressions to do this, or are you planning to replace all 4 digit numbers (surrounded with #)??
If it's for a single ID, you could use:
$replace_id = 2514;
$replacement_find = "#{$replace_id}#";
$replacement_replace = "<a href=\"mylink.php?{$replace_id}\">{$replace_id}</a>";
$text_final = str_replace($replacement_find, $replacement_replace, $text);
If you're doing multiple replacements (or, as per comment, not knowing any IDs) you can use this:
$text_final = preg_replace('@#([0-9]+?)#@', '<a href="mylink.php?$1">$1</a>', $text);
EDIT: From your comment, you could use preg_match_all to get all IDs in an array that are contained within the string. In the following code, $matches[1] contains the value of everything within the ()s in the regular expression, see return of print_r.
preg_match_all('@#([0-9]+?)#@', $text, $matches);
print_r($matches[1]);
To accommodate your latest request, you can use preg_replace_callback to get what you want:
function callback($matches) {
return '<a href="mylink.php?' . $matches[1] . '>' . getProductName($matches[1]) . '</a>';
}
$text_final = preg_replace_callback('@#([0-9]+?)#@', "callback", $text);