Which regex should I use?
I am writing an application in PHP and I need to replace any word between <!-- *
and * -->
its corresponding element in $vars
. For example,
<!-- *foobar* -->
In this case, 'foobar' should be replaced with the value of the variable $vars["foobar"]
. This is what I have now, but it doesn't work (it always returns <>
:():
preg_replace_callback("<!--(\s+)\*([a-zA-Z0-9]+)\*(\s+)-->", create_function('$matches', 'return $vars[$matches];'), $template);
Can anyone help me? Thanks in advance.
Remember that you cannot use $ vars without a view with the global keyword or with $ GLOBALS. Also, if you are using PHP 5.3, you can use an anonymous function without the ugly global hack:
$template = preg_replace_callback('/<!--\s+\*(\w+)\*\s+-->/', function($matches) use ($vars) { return $vars[$matches[1]]; }, $template);
In pre-5.3, you can do this:
$template = preg_replace_callback('/<!--\s+\*(\w+)\*\s+-->/', create_function('$matches', 'return $GLOBALS["vars"][$matches[1]];'), $template);
If you are not using 5.3, but still want to avoid the global variable, you can do this:
$template = preg_replace('/<!--\s+\*(\w+)\*\s+-->/e', '$vars["\1"]', $template);
source to share
Try:
create_function('$matches', 'return $vars[$matches[2]];')
since the second group is the one you want. Not sure why you are capturing others. Also for this kind of thing I prefer global over challenge create_function()
.
Also, you are not constraining the regex like this version with /:
$vars = array(...);
preg_replace_callback('/<!--\s+\*([a-zA-Z0-9]+)\*\s+-->/', 'replace_var', $template);
function replace_var($matches) {
global $vars;
return $vars[$matches[1]];
}
source to share
I think what you need is:
preg_replace_callback("/<!--\s+\*([a-zA-Z0-9]+)\*\s+-->/", create_function('$matches', 'return $vars[$matches[2]];'), $template);
The $ matches variable is an array. Index 0 is what matches the entire regex, and then any additional indices are capturing groups (if any) in the regex.
In this case, $ match will look like this:
array(2) {
[0]=>
string(18) "<!-- *example* -->"
[1]=>
string(7) "example"
}
source to share