Php 我必须使用什么正则表达式?

Php 我必须使用什么正则表达式?,php,regex,Php,Regex,我正在用PHP编写一个应用程序,我需要将之间的任何单词替换为$vars中对应的元素。 比如说, <!-- *foobar* --> 有人能帮我吗?提前感谢。试试: create_function('$matches', 'return $vars[$matches[2]];') 因为第二组是你想要的。不知道你为什么要抓到其他人。同样对于这类事情,我倾向于使用全局函数,而不是调用create\u function() 此外,您没有对正则表达式进行定界,就像这个版本使用/: $var

我正在用PHP编写一个应用程序,我需要将
之间的任何单词替换为
$vars
中对应的元素。 比如说,

<!-- *foobar* -->
有人能帮我吗?提前感谢。

试试:

create_function('$matches', 'return $vars[$matches[2]];')
因为第二组是你想要的。不知道你为什么要抓到其他人。同样对于这类事情,我倾向于使用全局函数,而不是调用
create\u function()

此外,您没有对正则表达式进行定界,就像这个版本使用/:

$vars = array(...);
preg_replace_callback('/<!--\s+\*([a-zA-Z0-9]+)\*\s+-->/', 'replace_var', $template);

function replace_var($matches) {
  global $vars;
  return $vars[$matches[1]];
}
$vars=array(…);
preg_replace_回调('/'、'replace_var'、$template);
函数替换变量($matches){
全球$vars;
返回$vars[$matches[1]];
}

我认为您需要的是:

preg_replace_callback("/<!--\s+\*([a-zA-Z0-9]+)\*\s+-->/", create_function('$matches', 'return $vars[$matches[2]];'), $template);
preg_replace_回调(“/”,创建_函数(“$matches”,“return$vars[$matches[2]];”),$template);
$matches变量是一个数组。索引0是与整个正则表达式匹配的,然后任何其他索引都是正则表达式中的捕获组(如果有)

在本例中,$matches将如下所示:

array(2) {
  [0]=>
  string(18) "<!-- *example* -->"
  [1]=>
  string(7) "example"
}
数组(2){
[0]=>
字符串(18)”
[1]=>
字符串(7)“示例”
}

请记住,如果不使用带有全局关键字的at或使用$GLOBALS,就不能使用$vars。此外,如果您运行的是PHP 5.3,那么您可以使用匿名函数,而不必进行难看的全局攻击:

$template = preg_replace_callback('/<!--\s+\*(\w+)\*\s+-->/', function($matches) use ($vars) { return $vars[$matches[1]]; }, $template);
$template=preg_replace_回调('/',函数($matches)use($vars){return$vars[$matches[1]];},$template);
在5.3之前的版本中,您可以执行以下操作:

$template = preg_replace_callback('/<!--\s+\*(\w+)\*\s+-->/', create_function('$matches', 'return $GLOBALS["vars"][$matches[1]];'), $template);
$template = preg_replace('/<!--\s+\*(\w+)\*\s+-->/e', '$vars["\1"]', $template);
$template=preg_replace_回调('/',create_函数('$matches','return$GLOBALS[“vars”][$matches[1]];'),$template);
如果您不运行5.3,但仍希望避免使用全局变量,则可以执行以下操作:

$template = preg_replace_callback('/<!--\s+\*(\w+)\*\s+-->/', create_function('$matches', 'return $GLOBALS["vars"][$matches[1]];'), $template);
$template = preg_replace('/<!--\s+\*(\w+)\*\s+-->/e', '$vars["\1"]', $template);
$template=preg_replace('//e','$vars[“\1”]',$template);

为什么要匹配空格“(\s+”)和实际单词“([a-z…])”?它不应该是“”?@Dana:PHP给了我一个错误:编译失败:在偏移量6Oh处没有重复的内容,并且必须转义星号:)Too我可以看到我在*之前漏掉了反斜杠。这可能是问题所在吗?