PHP:preg_replace(),`e`-modifier和object

I'm writing a method which returns an function argument by its number.

protected function parseArgs($str, $args)
{
    return preg_replace('|#(\d)|e', '$args[\\1 - 1]', $str);
}

$str - a string with '#N' where N is a number of argument $args - array of arguments

So if i write '#1' - it returns $arg[0], the first argument. It works with string arguments, integers... But don't work with object as argument. In returns string Object. How do i get the object with this function?

You cannot get it to work like that, because preg_replace always returns a string. In fact this version also fails to preserve the type of all other non-string values, which means that after parseArgs is called you cannot distinguish between e.g. null, false and '' as values.

That said, what is the purpose of this function anyway? Why would I write this

$args = ('foo', 'bar');
$value = parseArgs('#1', $args);

instead of this?

$args = ('foo', 'bar');
$value = $args[0];

The e modifier is deprecated. Its use is discouraged.

Instead, I would point you toward the preg_replace_callback() function, which also gives you the ability to call PHP code from a regex replace, but without the poor practices embodies in the e modifier.

Your original example code was trying to do the following:

return preg_replace('|#(\d)|e', '$args[\\1 - 1]', $str);
  • start with a string containing a hash followed by a digit
  • grab the contents of $args array element numbered one less than the digit.
  • replace the digit in the string with the content of the $args element.

As @Jon said, this isn't exactly the most useful thing that regex replace could be used for, but if you did need to do it, it can be done just as easily, and with better coding practices, using preg_replace_callback():

preg_replace_callback(
    '|#(\d)|',
    function($matches) use($args) {return $args[$matches[1]-1];},
    $str
);

The advantage here is that you now have a lot more flexibility in the replacement code.

Hope that helps. (I've put it on multiple lines to make it easier to read)

Note the above code assumes you're using PHP 5.3 or higher. If you're using an earlier version, you will need to use create_function() rather than an inline function.

I know that I haven't answered the question directly, but that's okay since @Jon has already addressed that side of things. But I hope answer this will guide you toward better code all the same.