javascript - How to make use of recursion in preg_replace_callback -
i have javascript function (not plain javascript)
function formatstring () { var args = jquery.makearray(arguments).reverse(); var str = args.pop(); return str.replace(/{\d\d*}/g, function () { return args.pop(); }); }
that use format string e.g formatstring("{0} , {1}", "first", "second");
returns "first , second"
i want replicate same functionality in php , have following function:
function formatstring() { if(func_num_args() > 1) { $args = array_reverse(func_get_args()); $input = array_pop($args); } return preg_replace_callback('/{\d\d*}/', function() use ($args) { return array_pop($args); }, $input); }
however, in case formatstring("{0} , {1}", "first", "second");
returns "first , first"
unlike javascript version of function callback executes every match, php variation seems execute callback once.
i considering making recursive call formatstring
callback since preg_replace_callback calls callback own arguments (here in array of matches) having challenge recursion.
please advise on how best utilize callback or alternative solution using preg_replace_callback
. use of global variables out of question.
your problem: php pass-by-value. consider this:
function pop_it($array) { array_pop($array); print_r($array); } $array = array(1, 2); print_r($array); // => array([0] => 1, [1] => 2) pop_it($array); // => array([0] => 1) print_r($array); // => array([0] => 1, [1] => 2)
your function called fine. same argument, since $args
never changes. not matters - outside callback. need pass-by-reference make change stick.
change function pop_it(&$array)
(or use (&$args)
), and... happens.
however, not approach, wrong thing formatstring("{1} , {0}", "second", "first")
, formatstring("{0} , {0}", "only")
. i'd pluck index out regexp , find in array. (also, \d\d*
less legible than, equivalent to, \d+
.)
Comments
Post a Comment