preg_replace_callback with local variable access


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. <?php
  2. function curry($func, $arity) {
  3. return create_function('', "
  4. \$args = func_get_args();
  5. if(count(\$args) >= $arity)
  6. return call_user_func_array('$func', \$args);
  7. \$args = var_export(\$args, 1);
  8. return create_function('','
  9. \$a = func_get_args();
  10. \$z = ' . \$args . ';
  11. \$a = array_merge(\$z,\$a);
  12. return call_user_func_array(\'$func\', \$a);
  13. ');
  14. ");
  15. }
  16.  
  17. function on_match($transformation, $matches)
  18. {
  19. return $transformation[strtolower($matches[1])];
  20. }
  21.  
  22. $transform = array('a' => 'Well,', 'd'=>'whatever', 'b'=>' ');
  23.  
  24. $callback = curry(on_match, 2);
  25. echo preg_replace_callback('/([a-z])/i', $callback($transform), 'Abcd');
  26.  
  27. echo "\n";
  28. ?>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.