Return to Snippet

Revision: 31041
at August 27, 2010 23:50 by freezy


Initial Code
<?php
function curry($func, $arity) {
    return create_function('', "
        \$args = func_get_args();
        if(count(\$args) >= $arity)
            return call_user_func_array('$func', \$args);
        \$args = var_export(\$args, 1);
        return create_function('','
            \$a = func_get_args();
            \$z = ' . \$args . ';
            \$a = array_merge(\$z,\$a);
            return call_user_func_array(\'$func\', \$a);
        ');
    ");
}

function on_match($transformation, $matches)
{
    return $transformation[strtolower($matches[1])];
}

$transform = array('a' => 'Well,', 'd'=>'whatever', 'b'=>' ');

$callback = curry(on_match, 2);
echo preg_replace_callback('/([a-z])/i', $callback($transform), 'Abcd');

echo "\n";
?>

Initial URL
http://www.php.net/manual/en/function.preg-replace-callback.php#88000

Initial Description
To access a local variable within a callback, use currying (delayed argument binding).\r\nThe magic lies in this curry found here: http://www.sitepoint.com/forums/showthread.php?threadid=336758

Initial Title
preg_replace_callback with local variable access

Initial Tags

                                

Initial Language
PHP