【问题标题】:How to replace placeholders with actual values?如何用实际值替换占位符?
【发布时间】:2012-01-13 05:12:28
【问题描述】:

我需要一个函数,用正确的变量替换“{}”中的每个变量名。 像这样的:

$data["name"] = "Johnny";
$data["age"] = "20";

$string = "Hello my name is {name} and I'm {age} years old.";

$output = replace($string, $data);
echo $output;

//outputs: Hello my name is Johnny and I'm 20 years old.

我知道为此有框架/引擎,但我不想为此安装一堆文件。

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以使用preg_replace/e 修饰符最轻松地做到这一点:

    $data["name"] = "Johnny";
    $data["age"] = "20";
    
    $string = "Hello my name is {name} and I'm {age} years old.";
    
    echo preg_replace('/{(\w+)}/e', '$data["\\1"]', $string);
    

    See it in action.

    您可能想要自定义匹配替换字符串的模式(这里是{\w+}:一个或多个字母数字字符或大括号之间的下划线)。把它放到一个函数中是微不足道的。

    【讨论】:

    • 不错的解决方案,+1。虽然我会使用 [^\}]+ 而不是 \w
    【解决方案2】:

    给你:

    $data["name"] = "Johnny";
    $data["age"] = "20";
    
    $string = "Hello my name is {name} and I'm {age} years old.";
    
    foreach ($data as $key => $value) {
    $string = str_replace("{".$key."}", $value, $string);
    }
    
    echo $string;
    

    【讨论】:

      【解决方案3】:

      您可能想看看preg_replace 函数。

      【讨论】:

        【解决方案4】:
        $string = "Hello my name is {$data["name"]} and I'm {$data["age"]} years old.";
        

        会做你想做的事。如果它不适合您,请尝试使用正则表达式进行循环,就像这样

        for ($data as $key=>$value){
            $string = preg_replace("\{$key\}", $value, $string);
        }
        

        未经测试,您可能需要查阅文档。

        【讨论】:

        • 这里使用preg_replace而不是str_replace有什么特别的原因吗?
        【解决方案5】:

        你可以试试vsprintf,它的语法略有不同

        $string = 'hello my name is %s and I am %d years old';
        
        $params = array('John', 29);
        
        var_dump(vsprintf($string, $params));
        //string(43) "hello my name is John and I am 29 years old" 
        

        【讨论】:

          【解决方案6】:

          我一直是strtr的粉丝。

          $ php -r 'echo strtr("Hi @name. The weather is @weather.", ["@name" => "Nick", "@weather" => "Sunny"]);'
          Hi Nick. The weather is Sunny.
          

          这样做的另一个好处是您可以定义不同的占位符前缀类型。这就是 Drupal 的做法; @ 表示要转义的字符串以安全地输出到网页(以避免注入攻击)。 format_string 命令循环遍历您的参数(例如@name@weather),如果第一个字符是@,那么它在值上使用check_plain

          也在这里回答:https://stackoverflow.com/a/36781566/224707

          【讨论】:

            猜你喜欢
            • 2017-07-28
            • 1970-01-01
            • 2014-12-09
            • 1970-01-01
            • 1970-01-01
            • 2017-09-11
            • 2013-01-24
            • 2020-06-13
            • 2013-04-08
            相关资源
            最近更新 更多