In preg_replace_callback, function ($ match) use ($ ten)

Source: Internet
Author: User
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,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.