我从此链接借用了代码 PHP正则表达式模板 - 查找全部发生{{var}} 以实现将值应用于模板文件的方法。这使用了preg_replace_callback()函数

我首选的命名方法是name1.name2.name3 = value,而不是name1_name2_name3 = value,但我正在使用的正则表达式似乎有问题。

这个不起作用。

模板文件

.aclass{
  font-width:{{newsflash.font.width}};
}

.ini值

newsflash.font.width=8px

使用正则表达式

'!\{\{(\w+).+\.\w+\}\}!'

print_r的输出($匹配)

Array
(
  [0] => {{newsflash.font.width}}
  [1] => newsflash
)

替换错误,因为$ matches [1]是错误的密钥。

.aclass{
  font-width:;
}

我怀疑有些库已经提供了这个功能,并且很想知道它们,但我仍然想知道正则表达式的错误。

错误的正则表达式的完整代码如下。

$inputFileName = 'templateVars.css';
$outputFileName = 'templateVals.css';
$varsFileName = 'variables.ini';

$ini_array = parse_ini_file($varsFileName);
$matchesArray = array();

function replace_value($matches) {
  global $ini_array;
  global $matchesArray;
  print "<pre>";
  print_r($matches);
  print "</pre>";
  return $ini_array[$matches[1]];
}


$inputFileVar = file_get_contents($inputFileName);

print "<pre>";
print_r($ini_array);
print "</pre>";


print "<pre>";
print $inputFileVar;
print "</pre>";

$outFileVar = preg_replace_callback('!\{\{(\w+).+\.\w+\}\}!', 'replace_value', $inputFileVar);

print "<pre>";
print $outFileVar;
print "</pre>";

print "<pre>";
print $matchesArray;
print "</pre>";

要匹配的模板

.aclass{
  font-width:{{newsflash.font.width}};
  color:{{newsflash.font.color}}
}

.ini文件的内容

newsflash.font.width=8px
newsflash.font.color=red
有帮助吗?

解决方案

字符不是 \ w 的一部分;并且你的。+ (在分组parens之外)将匹配任何非空字符串(是通配符)。因此, $ matches [1] = newsflash 是正确的。

你认为 $ matches [1] 是什么?对不起,您的问题并不清楚。

其他提示

!\{\{(\w[\.\w]*)\}\};?!

此正则表达式似乎与您的模板匹配得很好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top