简体   繁体   English

php preg_replace匹配

[英]php preg_replace matches

How do you access the matches in preg_replace as a usable variable? 如何将preg_replace中的匹配作为可用变量进行访问? Here's my sample code: 这是我的示例代码:

<?php
$body = <<<EOT
Thank you for registering at <!-- site_name -->

Your username is: <!-- user_name -->

<!-- signature -->
EOT;

$value['site_name'] = "www.thiswebsite.com";
$value['user_name'] = "user_123";

$value['signature'] = <<<EOT
live long and prosper
EOT;

//echo preg_replace("/<!-- (#?\w+) -->/i", "[$1]", $body);
echo preg_replace("/<!-- (#?\w+) -->/i", $value[$1], $body);
?>

I keep getting the following error message: 我一直收到以下错误消息:

Parse error: syntax error, unexpected '$', expecting T_STRING or T_VARIABLE on line 18 解析错误:语法错误,意外的'$',在第18行期待T_STRING或T_VARIABLE

The above remarked line with "[$i]" works fine when the match variable is enclosed in a quotes. 当匹配变量用引号括起来时,上面带有“[$ i]”的注释行正常工作。 Is there a bit of syntax I'm missing? 我缺少一些语法吗?

Like this: echo preg_replace("/<!-- (#?\\w+) -->/", '$1', $body); 像这样: echo preg_replace("/<!-- (#?\\w+) -->/", '$1', $body);

The /i modifier can only do harm to a pattern with no cased letters in it, incidentally. 顺便说一句, /i修饰符只会对其中没有套接字母的图案造成伤害。

You can't use preg_replace this way. 你不能这样使用preg_replace It doesn't define a variable named $1 that you can interact without outside the replacement; 它没有定义一个名为$1的变量,您可以在没有替换之外进行交互; the string '$1' is simply used internally to represent the first sub-expression of the pattern. 字符串'$1'仅在内部用于表示模式的第一个子表达式。

You'll have to use a preg_match to find the string matched by (#?\\w+) , followed by a preg_replace to replace matched string with the corresponding $value : 您必须使用preg_match来查找匹配的字符串(#?\\w+) ,然后使用preg_replace将匹配的字符串替换为相应的$value

$value['site_name'] = "www.thiswebsite.com";
$value['user_name'] = "user_123";
$value['signature'] = "something else";

$matches = array();
$pattern = "/<!-- (#?\w+) -->/i";

if (preg_match($pattern, $body, $matches)) {
  if (array_key_exists($matches[1], $value)) {
    $body = preg_replace($pattern, '<!-- ' . $value[$matches[1]] . ' -->', $body);
  }
}

echo $body;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM