PHP正则表达式模板-查找所有出现的{{var}} [英] PHP regex templating - find all occurrences of {{var}}

查看:90
本文介绍了PHP正则表达式模板-查找所有出现的{{var}}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为我的PHP脚本创建正则表达式时,我需要一些帮助.基本上,我有一个包含我的数据的关联数组,并且我想使用preg_replace用真实数据替换一些占位符.输入将是这样的:

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-holders with real data. The input would be something like this:

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

我不想使用str_replace,因为该数组可能包含比我需要的更多的项目.

I don't want to use str_replace, because the array may hold many more items than I need.

如果我理解正确,则preg_replace能够获取从正则表达式中找到的文本,并将其替换为数组中该键的值,例如

If I understand correctly, preg_replace is able to take the text that it finds from the regex, and replace it with the value of that key in the array, e.g.

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

替换为 $ replace ['address'] 的值.这是真的,还是我误读了php文档?

get replaced with the value of $replace['address']. Is this true, or did I misread the php docs?

如果这是真的,请有人帮我给我看一个正则表达式,它将为我解析(如果您也解释它的工作原理,将不胜感激,因为我对正则表达式还不太满意).

If it is true, could someone please help show me a regex that will parse this for me (would appreciate it if you also explain how it works, since I am not very good with regexes yet).

非常感谢.

推荐答案

使用 preg_replace_callback() .对于这种事情,它非常有用.

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

基本上,这表示找到所有包含单词字符的{{...}},并将该值替换为查找表中的值(即全局$ replace_values).

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).

这篇关于PHP正则表达式模板-查找所有出现的{{var}}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆