函数内部的preg_replace变换参数

Is it possible to make preg_replace parse the variables inside a function?

I am looking to transform a [shorturl]full-url[/shorturl] into a clickable short url.

I want something like this:

    $code = array(
      ...
      '#\[shorturl\]((?:ftp|https?)://.*?)\[/shorturl\]#i' => '<a href="'.file_get_contents("http://...some_api?url=$1").'">$1</a>',
      ...
    )

   $result = preg_replace(array_keys($code), array_values($code), $text);

But this don't works... The api does receive the "$1" as the url rather than the actually url.

Any thoughts?

This cannot work.

Have a look in the execution sequence of your example: Any file_get_contents gets executed BEFORE your preg_replace get called.

But you want the result of the regular expression as a part of your function call. The solution: preg_replace_callback. This function calls your code every time a match is found. Example:

preg_replace_callback('#\[shorturl\]((?:ftp|https?)://.*?)\[/shorturl\]#i', 
    function($a) {
      return '<a href="'.
              file_get_contents('http://...some_api?url='.$a).
              '">'.$a.'</a>';
     }, $text
 );

I didn't test it, but to give you an idea.