dpzbzp8728 2014-07-04 09:13
浏览 30
已采纳

在preg_replace之前获取更多信息

I have a script that replaces all BBCODES in comments to HTML.

I have managed to convert all the simple codes except the username code [user="max"] because I need to grab more user information such as user reputation & user online status from the database.

  $bbextended = array(
    "/\[url](.*?)\[\/url]/i" => "<a href=\"http://$1\" title=\"$1\">$1</a>",
    "/\[user=(.*?)\]/i" => "<div class=\"user\"> <a href=\"/user/$1\" title=\"$1\">$1</a><span> $USER REPUTATION </span></div>",
  );

  foreach($bbextended as $match=>$replacement){
    $bbtext = preg_replace($match, $replacement, $bbtext);
  }

Since preg_replace replaces matches inside it's function, I cannot get the username to grab other user information from the database.

  • 写回答

1条回答 默认 最新

  • dongzhi4498 2014-07-04 09:17
    关注

    You'll find you can massively expand your BBCode library if you use preg_replace_callback.

    Example:

    $bbextended = array(
      "/\[url](.*?)\[\/url]/i" => "<a href=\"http://$1\" title=\"$1\">$1</a>",
      "/\[user=(.*?)\][\/url]/i" => function($m) {
        $foo = "bar";
        return "<div class=\"user\" <a href=\"/user/".$m[1]."\" title=\"".$m[1]."\">"
                            .$m[1]."</a><span> ".$foo." </span></div>";
      }
    );
    
    foreach($bbextended as $match=>$replacement){
      if( is_callable($replacement)) {
        $bbtext = preg_replace_callback($match, $replacement, $bbtext);
      }
      else {
        $bbtext = preg_replace($match, $replacement, $bbtext);
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号