3

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'] = "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

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I need to use the $1 to index $value[$1].
@gurun8: Then you need to use preg_replace_callback() so you can execute code upon each match.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.