【问题标题】:Setting a parameter inside a string of an array在数组的字符串中设置参数
【发布时间】:2011-11-15 10:24:19
【问题描述】:

我有一个函数language($tag),它需要一个文件lang.php,其中包含一个名为$lang 的数组,其中包含一些参数。特别是字符串$lang['message']。在一些执行行之后,它返回$lang['message']

$lang 数组定义如下:

$lang[$tag] = array(
    'message' => 'This is a message',
    ...
);

现在假设我希望能够在$lang['message'] 中设置我应该能够在language($tag, $parameters) 上定义的参数。而这些参数应该在$lang['message']里面设置一个var比如:

$lang[$tag] = array(
    'message' => 'This is a '. $1,
    ...
);

如何组织language($tag, $parameters) 以使$parameters 中的内容将$1 中的$1 设置为$lang['message'] 的最佳方式是什么?

如果您不明白,我希望能够致电 language($tag, 'post') 并使其返回 'This is a post'

【问题讨论】:

    标签: php arrays function


    【解决方案1】:

    如何将字符串保存为printf 模板,例如

    $lang[$tag] = array(
        'message' => 'This is a %s'
    );
    

    然后您可以使用vsprintf 传递值替换数组,例如

    function language($tag, array $values)
    {
        // get $lang from somewhere
    
        return vsprintf($lang[$tag]['message'], $values);
    }
    

    【讨论】:

      【解决方案2】:

      一种解决方案可能是使用sprintf()

      'message' => 'This is a %s',
      

      而你只是这样使用它:

      sprintf($lang['message'], 'post');
      

      请阅读manual page of sprintf() 了解其众多功能。

      【讨论】:

        【解决方案3】:

        对于我的语言功能,我可能会选择 sprintf()

        解决方案可能如下所示:

        $lang = array(
            'stop' => 'Stop right there!',
            'message' => 'This is a %s',
            'double_message' => 'This is a %s with %s comments',
            ...
        );
        

        还有:

        function language()
        {
            $lang = get_lang_from_file(); // You probably have the idea
            $params = func_get_args();
        
        
            if(count($params) == 1)
                return $lang[$params[0]];
        
            $params[0] = $lang[$params[0]];
            return call_user_func_array("sprintf", $params);
        }
        

        这样你可以这样使用它:

        echo language('stop'); // outputs 'Stop right there!'
        echo language('message', 'message for you'); // outputs 'This is a message for you'
        echo language('double_message', 'message for you', '6'); // outputs 'This is a message for you with 6 comments
        

        【讨论】:

        • vsprintf()sprintf 好很多,来自call_user_func_array()
        猜你喜欢
        • 2017-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        • 2014-01-05
        相关资源
        最近更新 更多