将 preg_match 中的反向引用替换为字符串变量


Replacing back references in preg_match with string variables

我正在尝试模板化文档,我想通过在文档中搜索[%text%]并将其替换为$array['text']$text来用动态文本替换文档的部分。 我知道我可以使用str_replace("[%text%]", $array['text'], $page),但我想找到[%(.*?)%]的所有实例并替换为 $array[$1] 而不是 $1 . 我试过使用create_function($matches, $array),但它抱怨Missing argument 2 for {closure}().

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

你可以preg_match_all('#[%(.*?)%]#is', $page, $matches);然后

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
    }
  }
}

首先执行preg_match并找到匹配的名称。然后用替换每个找到的名称来替换数组。然后将数组中的 preg_replace 用作第二个参数,从而将名称替换为数组中的项。

你可以

用preg_replace_callback做到这一点。

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