In preg_replace_callback, function ($ match) use ($ ten)
$string = "Some numbers: one: 1; two: 2; three: 3 end";$ten = 10;$newstring = preg_replace_callback( '/(\\d+)/', function($match) use ($ten) { return (($match[0] + $ten)); }, $string );echo $newstring;
Reply to discussion (solution)
Use
Function ($ match) use ($ ten) {return ($ match [0] + $ ten ));}
Make the variable $ ten available in anonymous functions
Equivalent
$ Ten = 10;
Function foo ($ match ){
Global $ ten;
Return ($ match [0] + $ ten ));
}
However, if $ ten is not a global variable, it will be troublesome.
Closure syntax added in php 5.3
Closure functions (anonymous functions) can inherit variables from the parent scope. any such variables should be passed in using the use language structure.
Use
Function ($ match) use ($ ten) {return ($ match [0] + $ ten ));}
Make the variable $ ten available in anonymous functions
Equivalent
$ Ten = 10;
Function foo ($ match ){
Global $ ten;
Return ($ match [0] + $ ten ));
}
However, if $ ten is not a global variable, it will be troublesome.
Can it be replaced in 5.2?
Can I do it if it is not a global variable? $ Ten;
Closure syntax added in php 5.3
Closure functions (anonymous functions) can inherit variables from the parent scope. any such variables should be passed in using the use language structure.
5.2 cannot be used? Is there any replacement method?
5.2 cannot be used. you can do this.
$string = "Some numbers: one: 1; two: 2; three: 3 end";$ten = 10;$newstring = preg_replace_callback( '/(\\d+)/', create_function('$match', "return \$match[0] + $ten;"), $string );echo $newstring;
5.2 cannot be used. you can do this.
$string = "Some numbers: one: 1; two: 2; three: 3 end";$ten = 10;$newstring = preg_replace_callback( '/(\\d+)/', create_function('$match', "return \$match[0] + $ten;"), $string );echo $newstring;
Thank you,