1

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?

5
  • 1
    Take a look at preg_replace_callback(). Also since you then need access to dynamic variable names in the callback you will need to use global with variable variables. Commented May 1, 2016 at 18:13
  • Or, in addition to @Rizier123, the use command. Commented May 1, 2016 at 18:14
  • @Jan OP won't be able to use 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 in use(). Commented May 1, 2016 at 18:15
  • @Rizier123: See my answer with using use in the callback function. Commented May 1, 2016 at 18:20
  • What are the requirements for "variable_name"? Commented May 1, 2016 at 18:39

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.