0

I'm trying to rewrite this function

<?php
    $vars = array('id'=>$_SESSION['id'], 'name' => $_SESSION['username'],
'time' => $time->format('Y-m-d H:i:s');
    $filename = "@name - @time";
    echo preg_replace('/@(\w+)/e', '$vars["$1"]', $filename);
    ?>

So far, this is where I got

<?php
    $vars = array('id'=>$_SESSION['id'], 'name' => $_SESSION['username'],
'time' => $time->format('Y-m-d H:i:s');
    $filename = "@name - @time";
    echo preg_replace_callback('/@(\w+)/', function ($matches) {return '$vars["$1"]';}, $filename);
    ?>

But this only shows me $vars["$1"] - $vars["$1"] , so I'm obviously doing something wrong. Even after reading the documentation I don't really understand what I'm doing. Can anyone help me out?

Sorin Lascu
  • 395
  • 1
  • 4
  • 15
  • Do you want that: `'$vars["$1"]'` This is interpreted as a string or as a variable ? (Also change: `'$vars["$1"]'` to this: `'$vars["' . $matches[1] . ']'`, since your matches are in `$matches`) – Rizier123 May 27 '15 at 09:54
  • It's supposed to replace something like @data with $vars['data'] . Thanks for attempting to help me. – Sorin Lascu May 27 '15 at 11:32

1 Answers1

0

Try below, and it will retain @foo if index foo is not found in $vars.

You also need to use use ($vars) to import $vars to the scope of callback function.

echo preg_replace_callback('/@(\w+)/', function($matches) use ($vars) {
  return isset($vars[$matches[1]]) ? $vars[$matches[1]] : '@'.$matches[1];
}, $filename);
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 1. No explanation, what you changed and why you changed the code; What OP did wrong and how it is done 2. It's not clear if he wants the value out of `$vars` or just a string. From a 94k guy, really poor answer – Rizier123 May 27 '15 at 09:59
  • Ok, this works. Thanks for the help, now I'm going to try and dissect your code to understand better. – Sorin Lascu May 27 '15 at 11:31