Fastest way to replace string patterns by mask

php

Solution

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

Problem

I have string like ``` $string = "string_key::%foo%:%bar%"; ``` , and array of params ``` $params = array("foo" => 1, "bar" => 2); ``` How can I replace this params in $string pattern? Expected result is ``` string_key::1:2 ```

Original source