doubiankang2845 2012-12-08 21:45
浏览 44

如何在PHP中操作变量占位符?

Without resorting to using regex, is there a way to do so if I saved my array into json format? I'm interesting in json only because I'm using mongodb so the output comes out in json format. I have a field called docroot which is essentially a directory path.

docroot : "secure.unstable.qa.example.com"

The only two pieces that could change depending on other factors are unstable and qa. What I'm hoping for is a way to place "markers" so that they could easily be replaced with an appropriate variable.

For example:

docroot : "secure.{STREAMS}.{ENV}.example.com"
docroot : "unsecure.{STREAMS}.{ENV}.example.com"
  • 写回答

1条回答 默认 最新

  • douhu2890 2012-12-09 02:11
    关注

    If the variables are guaranteed to be in some specific order (they are, according to your example), then I would advise not reinventing the wheel:

    // Assuming $json contains your JSON
    
    $streams = 'foo';
    $env = 'bar';
    $data = json_decode($json, TRUE);
    
    var_dump($data['docroot']); // "secure.%s.%s.example.com"
    var_dump(sprintf($data['docroot'], $streams, $env)); // "secure.foo.bar.example.com"
    

    If the variables are not guaranteed, or you'd just like to use more descriptive placeholders, just pick some unique delimiters (some character or set of characters that is unlikely to actually appear in your data), and use str_replace().

    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上