Fastest way to replace string patterns by mask

后端 未结 1 634
独厮守ぢ
独厮守ぢ 2021-02-14 18:41

I have string like

$string = \"string_key::%foo%:%bar%\";

, and array of params

$params = array(\"foo\" => 1, \"bar\" =>         


        
1条回答
  •  清歌不尽
    2021-02-14 19:17

    First, you need to rewrite the $params array:

    $string = "string_key::%foo%:%bar%";
    $params = array("foo" => 1, "bar" => 2);
    foreach($params as $key => $value) {
        $search[] = "%" . $key . "%";
        $replace[] = $value;
    }
    

    After that, you can simply pass the arrays to str_replace():

    $output = str_replace($search, $replace, $string);
    

    View output on Codepad

    0 讨论(0)
提交回复
热议问题