How to replace {tag_INDEX} with an array [INDEX]

I have a line like this:

"String {tag_0} text {tag_2} and {tag_1}"

Now I need to replace all {tag_INDEX} with elements from the array

$myArray = array('a','b','c');

so after replacing it should look like this:

"String of text c and b"

What is the best way to do this? I try with preg_replace and preg_replace_callback but without good results

+3
source share
3 answers
$newStr = preg_replace('/{tag_(\d+)}/e', '$myArray[\1]', $str);
+6
source

No regex required:

$s = "String {tag_0} text {tag_2} and {tag_1}";
$myArray = array('a','b','c');

$s = template_subst($s, $myArray);
echo $s;

// generic templating function
function template_subst($str, &$arr) {
  foreach ($arr as $i => &$v) {
    $str = str_replace("{tag_$i}", $v, $str);
  }
  return $str;
}
+1
source

Run an iterative regular expression with a limit of 1 at each iteration and replace your expression with $ myArray [n].

0
source

Source: https://habr.com/ru/post/1746977/


All Articles