douquan1015 2013-10-07 01:04
浏览 20
已采纳

函数内部的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?

  • 写回答

1条回答 默认 最新

  • douchenchepan6465 2013-10-07 01:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决