3

Ok so I'm trying to do something like so:

preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);

Now I know that is not possible like it is, however I would like to know if there is a way to do this, because I have tried to use create_function however, $templateVariables is a local variable to the function that it is within, so I can't access $templateVariables from within create_function, so I'm kind of stuck here. I would rather not have to find the matches figure out what to replace them with and then find them again to replace, that just seems horrible inefficient. So is there anyway I can get to a local variable from within an anonymous function or does anyone have any good suggestions.

Thanks.

3 Answers 3

4

Try this:

$vars = array(
    "test" => "Merry Christmas",
);
$string = "test {test} test";
$string = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function($match) use ($vars) {
    return isset($vars[$match[1]]) ? $vars[$match[1]] : $match[0];
}, $string);
echo $string;

It should output:

test Merry Christmas test

You can see a working example here http://codepad.viper-7.com/2ZNNYZ

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

6 Comments

pretty nifty trick. Is there a way to do this with a named callback function?
Define the callback function and than just place it's name as string in there.
@hakre: I don't understand. I know you can do preg_replace_callback("pattern","someFunction","subject"); and then have a separate function someFunction ($matches) {...} but for instance you cannot do preg_replace_callback("pattern","someFunction($someVar)","subject"); my question is if there is a way to do that. Well, that's the OP's question really. I guess MY question is...you CAN pass var to anon function using "use" as shown in this answer. But can you do for instance preg_replace_callback("pattern","someFunction" use ($someVar) ,"subject");
@CrayonViolent preg_replace_callback("pattern",function($m) use ($someVar) { call_some_other_function($someVar, $m); },"subject"); and, no, the original question was "can I preg_replace using a match as an index of an array"
Is there documentation for this use of use that I can take a look at? I just wanna see where this was that I missed it
|
-1

You can actually use preg_replace with /e modifier:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", '$templateVariables[\'$1\']', $templateString)

But it may not be the safest way here...

Comments

-1

You need to use e regexp modifier:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", "\$templateVariables['\\1']", $templateString);

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.