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

I need help 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 owners with real data. The input will be something like this:

<td>{{address}}</td><td>{{fixDate}}</td><td>{{measureDate}}</td><td>{{builder}}</td> 

I do not want to use str_replace because the array can contain much more elements than I need.

If I understand correctly, preg_replace can take the text that it finds from the regular expression and replace it with the value of this key in the array, for example.

 <td>{{address}}</td> 

replace with the value $ replace ['address']. Is this true, or am I reading php documents incorrectly?

If this is true, can someone please help show me a regular expression that will analyze this for me (it would be appreciated if you also explained how this works, as long as I am not very good with regular expressions).

Thank you very much.

+4
source share
3 answers

Use preg_replace_callback() . It is 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 indicates that all occurrences of {{...}} containing words are detected and replaces this value with the value from the lookup table (which is the global value of $ replace_values).

+8
source

For a well-formed XML / XML analysis, consider using the Document Object Model (DOM) in conjunction with XPath . This is much more interesting to use than regular expressions for this kind of thing.

0
source

In order not to use global variables and gracefully handle missing keys, you can use

 function render($template, $vars) { return \preg_replace_callback("!{{\s*(?P<key>[a-zA-Z0-9_-]+?)\s*}}!", function($match) use($vars){ return isset($vars[$match["key"]]) ? $vars[$match["key"]] : $match[0]; }, $template); } 
0
source

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


All Articles