I have a substring like {[variable_name]} and want to replace it with the value of the variable specified in brackets.
/\{\[\s*[^0-9][a-zA-Z0-9_]*\s*]}/
This is my regular expression, but I have no idea, what i should do next. How do I?
In addition to the comment, this would work:
<?php
$replacements = array();
$replacements["var1"] = "New variable here";
$regex = '~\{\[([^]]+)\]}~';
$string = "This is some string with {[var1]} in it";
$string = preg_replace_callback(
$regex,
function ($match) use ($replacements) {
return $replacements[$match[1]];
},
$string);
echo $string;
# This is some string with New variable here in it
?>
See a demo on ideone.com.
preg_replace_callback(). Also since you then need access to dynamic variable names in the callback you will need to useglobalwith variable variables.usecommand.use(). Think about it: OP will get the value of the variable name in the matches array, which gets passed to the callback. So he can't use it inuse().usein the callback function.