tags:

views:

461

answers:

5

Would it be possible to make a regex that reads {variable} like <?php echo $variable ?> in PHP files?

Thanks

Remy

A: 

{Not actually an answer, but need clarification}

Could you expand your question? Are you wanting to apply a regex to the contents of $variable?

Suroot
i want to be able to type {variable} instead of <?php echo $variable ?>.
@Suroot: Comments are usually used for this kind of question :)
Ross
@Ross: Suroot doesn't have enough rep to post comments. :)
Pourquoi Litytestdata
A: 

The following line should replace all occurences of the string '{variable}' with the value of the global variable $variable:

$mystring = preg_replace_callback(
  '/\{([a-zA-Z][\w\d]+)\}/', 
  create_function('$matches', 'return $GLOBALS[$matches[1]];'), 
  $mystring);

Edit: Replace the regex used here by the one mentioned by Gumbo to precisely catch all possible PHP variable names.

cg
+2  A: 

The PHP manual already provides a regular expression for variable names:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

You just have to alter it to this:

\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\}

And you’re done.


Edit   You should be aware that a simple sequential replacment of such occurrences as Ross proposed can cause some unwanted behavior when for example a substitution also contains such variables.

So you should better parse the code and replace those variables separately. An example:

$tokens = preg_split('/(\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i=1, $n=count($tokens); $i<$n; $i+=2) {
    $name = substr($tokens[$i], 1, -1);
    if (isset($variables[$name])) {
        $tokens[$i] = $variables[$name];
    } else {
        // Error: variable missing
    }
}
$string = implode('', $tokens);
Gumbo
I think he wants to replace the php tags and also the echo function with the braces, not just the dollar sign.
CodeMonkey1
+3  A: 

It sounds like you're trying to do some template variable replacement ;)

I'd advise collecting your variables first, in an array for example, and then use something like:

// Variables are stored in $vars which is an array
foreach ($vars as $name => $value) {
    $str = str_replace('{' . $name . '}', $value, $str);
}
Ross
A: 

(in comments) i want to be able to type {variable} instead of <?php echo $variable ?>

Primitive approach: You could use an external program (e.g. a Python script) to preprocess your files, making the following regex substitution:

"{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}"

with

"<?php echo $\g<1> ?>"

Better approach: Write a macro in your IDE or code editor to automatically make the substitution for you.

Zach Scrivena