I hava a string like:
$my_string = "RGB colors are xxx, xxx, xxx";
Also have an array:
$my_array = ["red", "green", "blue"];
I would like to get a string like:
echo $my_string; //RGB colors are red, green, blue
Is there a one liner that can make this replacements? That is a string with same placeholder that gets replaced with each value from the array.
Following line can do this. You can allow loop through array to replace all xxx with respective values in array
preg_replace('/xxx/',$my_array[2], preg_replace('/xxx/', $my_array[1], preg_replace('/xxx/', $my_array[0], $my_string, 1), 1), 1);
This is not as straightforward as it could be, because str_replace
is a global replace - the first call will replace all xxx
s with the replacement value. You can use preg_replace
, and call it multiple times with $limit=1
.
$my_string = "RGB colors are xxx, xxx, xxx";
$my_array = [ "red", "green", "blue" ];
$placeholder = '/xxx/';
foreach ($my_array as $color) {
$my_string = preg_replace($placeholder, $color, $my_string, 1);
}
Note that that modifies the original string; you should make a copy and use that instead of $my_string
inside the loop if you don't want that to happen.
You could also use sprintf
as suggested in the comments, with a little preparation:
$args = $my_array;
array_unshift($args, str_replace(['%','xxx'], ['%%','%s'], $my_string));
$result = call_user_func_array(sprintf, $args);
Try this:
$my_string = "RGB colors are TO_BE_REPLACE";
$my_array = ["red", "green", "blue"];
echo str_replace('TO_BE_REPLACE', implode(',', $my_array), $my_string); //RGB colors are red, green, blue