用字符串变量替换preg_match中的引用

I'm trying to template a document, I want to replace section of the document with dynamic text by searching a document for [%text%] and replacing it with $array['text'] or $text. I know I can use str_replace("[%text%]", $array['text'], $page), but I want to find all instances of [%(.*?)%] and replace with with $array[$1] instead of $1. I've tried using create_function($matches, $array), but it complains about Missing argument 2 for {closure}().

$page = preg_replace('#\[%(.*?)%\]#is', $array["$1"], $page);

You can preg_match_all('#[%(.*?)%]#is', $page, $matches); and then

if(count($matches == 2))
{
  $key = 0;
  foreach(array_unique($matches[0]) as $val)
  {
    if(isset($array[$key]))
    {
      $page = str_replace($val, $array[$key++], $page);
    }
    else
    {
      break; // more matches than array elements
    }
  }
}

First do a preg_match and find the matching names. Then craete the array with replacements for every found name. Then use preg_replace with the array as second argument, thereby replacing the names with the items from the array.

You can do it with preg_replace_callback.

<?php
$page = preg_replace_callback('#\[%(.*?)%\]#is',
  function ($m){
    GLOBAL $array;
    return $array[$m[1]];
  }
, $page);
?>