【问题标题】:Best way to do string format in PHP在 PHP 中进行字符串格式的最佳方法
【发布时间】:2014-02-09 05:17:19
【问题描述】:

我有以下 python 代码来格式化字符串,

endpoint = '/uri/{id}'
params = {'id': xxxx}
endpoint.format(**params)

这给了我以下结果,

'/uri/xxxx'

我需要在 PHP 中开发一个功能相同的函数,我找到了一个与此相关的 question,但我仍然对此不满意。

用 PHP 做这种事情的最好方法是什么?

提前致谢

【问题讨论】:

  • 这些答案非常准确。要么按照建议选择sprintf 格式,要么使用the custom code that works more like you're used to
  • @EmilioGort 我有一个字符串和参数作为数组,我需要用参数值替换那个字符串
  • @Wrikken 欢迎任何不同的方法
  • @JanithChinthana:不一样怎么办?更高效?无法击败sprintf。更像 Python?您只需需要为此编写代码,它不存在开箱即用。所以...除非你能特别地告诉我一种新方法应该与已经提供的方法有什么不同,否则我无法为你梦想太多;)

标签: php python string


【解决方案1】:

也许,这样的东西会满足你的需求:

function sformat($template, $params) {
    return str_replace(
        array_map(function($v){return '{'.$v.'}';},array_keys($params)),
        $params,
        $template
    );
}

echo sformat('/uri/{action}/{id}', $params = array(
    'id'=>'23',
    'action'=>'open'
));

【讨论】:

    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    相关资源
    最近更新 更多