0

It won't work, if you see anything wrong..

function replaceLink($matches){
    $final = '<img src=\''.$path[$matches[1]].'\' alt=\''.$data['alt'].'\'/>';
    return $final;
}
$message = preg_replace_callback('#\[img\]([1-3])\[/img\]#isU', 'replaceLink', $message);

How may I use variables which were declared outside of the function?

  • Wont work? Or doesn't work correctly? What is the value of `$message`? – Dale Feb 02 '14 at 17:04
  • You'll be more likely to get help if you can provide a link to a jsfiddle or something similar that demonstrates the problem. – kiprainey Feb 02 '14 at 17:23

2 Answers2

0

You aren't passing the function, you're passing a string:

$message = preg_replace_callback('...', 'replaceLink', $message);

It should be this:

$message = preg_replace_callback('...', replaceLink, $message);
maja
  • 17,250
  • 17
  • 82
  • 125
0

Calling function in this way

$message = preg_replace_callback('#\[img\]([1-3])\[/img\]#isU', 'replaceLink', $message);

is ok. And should work.

But I see that in your function replaceLink()

function replaceLink($matches){
    $final = '<img src=\''.$path[$matches[1]].'\' alt=\''.$data['alt'].'\'/>';
    return $final;
}

you use variables which are not defined in that frunction $path, $data. If they are defined outside the function and they are not global then they will be null inside replaceLink() and you should get error.

Try to use this code

$message = preg_replace_callback( 
    '#\[img\]([1-3])\[/img\]#isU', 
    function($matches) use ($path, $data) {
         $final = '<img src=\''.$path[$matches[1]].'\' alt=\''.$data['alt'].'\'/>';
         return $final;
    }, 
    $message 
);