PHP regex templating - find all occurrences of {{var}}

后端 未结 3 774
臣服心动
臣服心动 2020-12-04 00:01

I need some help with creating a regex for my php script. Basically, I have an associative array containing my data, and I want to use preg_replace to replace some place-ho

3条回答
  •  天涯浪人
    2020-12-04 00:29

    Use preg_replace_callback(). It's incredibly useful for this kind of thing.

    $replace_values = array(
      'test' => 'test two',
    );
    $result = preg_replace_callback('!\{\{(\w+)\}\}!', 'replace_value', $input);
    
    function replace_value($matches) {
      global $replace_values;
      return $replace_values[$matches[1]];
    }
    

    Basically this says find all occurrences of {{...}} containing word characters and replace that value with the value from a lookup table (being the global $replace_values).

提交回复
热议问题