开发者

php preg_replace matches

How do you access the matches in preg_replace as a usable variable? 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'] = "w开发者_如何学编程ww.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

The above remarked line with "[$i]" works fine when the match variable is enclosed in a quotes. Is there a bit of syntax I'm missing?


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

The /i modifier can only do harm to a pattern with no cased letters in it, incidentally.


You can't use preg_replace this way. It doesn't define a variable named $1 that you can interact without outside the replacement; the string '$1' is simply used internally to represent the first sub-expression of the pattern.

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:

$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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜