douqiu0351 2014-12-03 05:35
浏览 16
已采纳

我怎样才能获得这个preg_replace替换?

I'm trying to get a string with #hashtags and convert them into array keys! For example:

string = "hello #world";

I want to replace to "hello $line['world']";

I did this:

$query = mysql_query($sql);
while($line = mysql_fetch_assoc($query)) {
    $code = preg_replace("/(#(\w+))/", $line['$1'], $string);
    echo $code;
}

But I get this warning: "Undefined index: $1" and obviously the echo prints only "hello "

But if I put a valid $line key directly it show its content. Like this:

$query = mysql_query($sql);
while($line = mysql_fetch_assoc($query)) {
    $code = preg_replace("/(#(\w+))/", $line[name], $string);
    echo $code;
}

It shows me "hello nameFromDatabase" for each line of database...

How can I set this $line[XXX] on the preg_replace to get the name located at the #hashtag replacement?

  • 写回答

1条回答 默认 最新

  • drxrgundk062317205 2014-12-03 05:41
    关注

    You can't with preg_replace. When you call that function you pass in two arguments:

    1. "/(#(\w+))/"
    2. $line['$1']

    By the time preg is doing the replacement, it's already too late. The second argument has been evaluated and the preg_method cannot go back and re-evaulate the argument to what you want.

    preg_replace_callback can do what you want though:

    while($line = mysql_fetch_assoc($query)) {
        $code = preg_replace_callback(
           "/(#(\w+))/",
           function($matches) use ($line) {
              return $line[$matches[1]];
           },
           $string
        );
        echo $code;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目