用索引替换数组值的字符串参数

时间:2015-03-30 21:17:28

标签: php arrays string replace

是否有一些本机php接收字符串和数组作为参数并用字符串中的/它们各自的值替换数组索引?

类似的东西:

$myString = "{days} days left for {holiday}";
$params = array(
    "days" => 275,
    "holiday" => "Christmas"
);
echo _some_function($myString, $params);
//Outputs: "275 days left for Christmas"

3 个答案:

答案 0 :(得分:1)

_some_function($myString, $params){
   foreach($params as $k=>$v)
        $myString = str_replace("{".$k."}",$v,$mString);
   return $myString;
}

- 不要问:如果"天n#34;喜欢"假期"作为价值;)

答案 1 :(得分:1)

这应该适合你:

(这里我首先在键周围添加分隔符,然后使用strtr()替换值)

<?php

    $myString = "{days} days left for {holiday}";
    $delimiters = ["{", "}"];
    $params = [
        "days" => 275,
        "holiday" => "Christmas"
    ];

    function someCrazyFunction($myString, $params, $delimiters) {
        foreach($params as $k => $v) {
            $params[$delimiters[0] . $k . $delimiters[1]] = $v;
            unset($params[$k]);
        }

        return strtr($myString, $params);

    }


    echo someCrazyFunction($myString, $params, $delimiters);

?>

输出:

275 days left for Christmas

答案 2 :(得分:0)

谢谢大家的答案。 根据@ Rizier123和@superduperawesomephpexpert评论:

$myString = "{days} days left for {holiday}";
$params = array(
    "days" => 275,
    "holiday" => "Christmas"
);

$indexes = array_map(function($v){
    return '{'.$v.'}';
}, array_keys($params));

echo str_replace($indexes, $params, $myString);