Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_replace matches

Tags:

regex

php

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?

like image 592
gurun8 Avatar asked Sep 08 '26 12:09

gurun8


1 Answers

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.

like image 104
chaos Avatar answered Sep 11 '26 02:09

chaos