Search code examples
phppreg-match

How can I assign preg_match results directly to variables?


The following works in PHP:

preg_match("/a/", "a", $m);
list($zero) = $m;

But the following gives an error:

preg_match("/a/", "a", list($zero));

PHP documentation says list() is a language construct, but I'd like to understand specifically why this fails. Also, is there another way to assign results directly to variables (like sscanf())?


Solution

  • The answer I can provide is not really satisfying I suppose. list() is like you said a language construct and it simply does not work like you used it in your second example. This is per definition, and cannot be changed.

    I though of the use of extract() to get the variables, but this offends the PHP "strict standards, if you use it like this:

    preg_match("/a/", "a", extract($m, EXTR_PREFIX_ALL, 'preg'));
    
    Strict Standards:  Only variables should be passed by reference
    

    I guess you will have to use a two line solution anyway, because of the by reference passing of preg_match().