Matching php preg_replace

How do you access matches in preg_replace as a useful variable? Here is 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 get the following error message:

Parse error: syntax error, unexpected '$', expecting T_STRING or T_VARIABLE on line 18

The above marked line with "[$ i]" works fine when the match variable is enclosed in quotation marks. Is there a little syntax that I skip?

+3
source share
2 answers

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

A modifier /ican only harm a pattern, with no letters in it.

+3
source

preg_replace . $1, ; '$1' .

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

Source: https://habr.com/ru/post/1795618/


All Articles