How the PHP back reference is brought into the function parameter

Source: Internet
Author: User
Preg_replace ('/{get_ (\w+)}/', $arr [$], $content);


For a back reference, I need to pass the matching \w+ as a parameter, to the custom function, or as an index to the array.


Reply to discussion (solution)

Preg_replace_callback can callback the function, but how to match to, as the index of the array, this I can't find the method

Preg_replace ('/{get_ (\w+)}/e ', ' $arr [' $ '] ', $content);

$content = ' {get_abc} '; $arr [' abc '] = 123;echo preg_replace ('/{get_ (\w+)}/e ', ' $arr ["$"] ', $content);

The extended mode E represents Eval, which means that the second argument is executed as a PHP statement
However, this approach was abolished by the php5.5, because the dynamic interpretation of PHP statements There is a problem of efficiency and security

A reasonable approach is to use Preg_replace_callback
The following are 3 of the wording
$content = ' {get_abc} '; $arr [' abc '] = 123;echo preg_replace_callback ('/{get_ (\w+)}/', ' Back ', $content); function back ($ m) {  global $arr;  return $arr [$m [1];}
$content = ' {get_abc} '; $arr [' abc '] = 123;echo preg_replace_callback ('/{get_ (\w+)}/', create_function (' $m ', ' global $ Arr return $arr ["$m [1]"]; '), $content);
$content = ' {get_abc} '; $arr [' abc '] = 123;echo preg_replace_callback ('/{get_ (\w+)}/', function ($m) use ($arr) {return $ arr["$m [1]"];}, $content);
Clearly the 3rd is the clearest, but only in the php5.3 began to support
  • Related Article

    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.