views:

42

answers:

3

Hi,

I have string like this;

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

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

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

so after replacement it should looks like:

"String a text c and b"

What is the best way to do this? I'm trying with preg_replace and preg_replace_callback but without any good results

+6  A: 
$newStr = preg_replace('/{tag_(\d+)}/e', '$myArray[\1]', $str);
Alexander Konstantinov
Don't forget to assign the result of `preg_replace` either, it doesn't replace in place as some people often seem to believe.
Matthew Scharley
@Matthew, thanks, I've added an assignment to my answer in case somebody can be confused by this
Alexander Konstantinov
A: 

Run an iterative regex with limit 1 in each iteration and replace your expression with $myArray[n].

Jan Kuboschek
+1  A: 

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;
}
Tomalak
Out of curiosity, why do you pass the array by reference?
Matthew Scharley
@Matthew: Why not. There's not much point in copying it.
Tomalak