PHP 正则表达式模板 - 查找所有出现的 {{var}} [英] PHP regex templating - find all occurrences of {{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屋!