note 88013 added to function.preg-replace-callback
| From: | tijn at q-go dot com | Date: | Tue, 06 Jan 2009 10:01:02 +0000 |
| Subject: | note 88013 added to function.preg-replace-callback | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-148878@lists.php.net to get a copy of this message | ||
To access a local variable within a callback, use currying (delayed argument binding). For example
<?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";
?>
outputs:
"Well, whatever"
The magic lies in this curry function I found here: http://www.sitepoint.com/forums/showthread.php?threadid=336758
----
Server IP: 83.137.20.135
Probable Submitter: 77.242.113.138
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace-callback.php
Edit -- https://master.php.net/note/edit/88013
Del: integrated -- https://master.php.net/note/delete/88013/integrated
Del: useless -- https://master.php.net/note/delete/88013/useless
Del: bad code -- https://master.php.net/note/delete/88013/bad+code
Del: spam -- https://master.php.net/note/delete/88013/spam
Del: non-english -- https://master.php.net/note/delete/88013/non-english
Del: in docs -- https://master.php.net/note/delete/88013/in+docs
Del: other reasons-- https://master.php.net/note/delete/88013
Reject -- https://master.php.net/note/reject/88013
Search -- https://master.php.net/manage/user-notes.php