Questions about reverse reference usage of preg_replace () functions

Source: Internet
Author: User
About the reverse reference usage of the preg_replace () function. $ Array1array (array (ID & gt; 1, Name & gt; Xiao Wang), array (ID & gt; 2, Name & gt; Xiao Li); $ strAAA & nbsp; name & nbsp; CC & nbsp; DD; $ strBs + (w +) s + I; reverse reference usage of the preg_replace () function.

$ Array1 = array (
Array ('id' => '1', 'name' => 'Wang '),
Array ('id' => '2', 'name' => 'Lily ')
);

$ StrA = 'AA Name CC DD ';
$ StrB = '/\ s + (\ w +) \ s +/I ';
$ Html = preg_replace ($ strB, $ Array1 [0] ['$ {2}'], $ strA );
Echo $ Html;


As shown above, returning to reference $ {2} is okay as follows:
$Html=preg_replace($strB, ‘${2}’, $strA);


However, if I want to use the referenced string as the key name of the array, for example, $ array ['$ {1}']. An error is reported. How can this problem be solved?
Notice: Undefined index: in F: \ Web \ wwwroot \ CMS \ TemplateClass. php on line 236
------ Solution ----------------------
For php5.5, you can
$ Array1 = array (
Array ('id' => '1', 'name' => 'Wang '),
Array ('id' => '2', 'name' => 'Lily ')
);

$ StrA = 'AA Name CC DD ';
$ StrB = '/\ s + (\ w +) \ s +/ie ';
$ Html = preg_replace ($ strB, '$ Array1 [0] ["$1"]', $ strA );
Echo $ Html;

For php5.3 and above, you can
$ Array1 = array (
Array ('id' => '1', 'name' => 'Wang '),
Array ('id' => '2', 'name' => 'Lily ')
);

$ StrA = 'AA Name CC DD ';
$ StrB = '/\ s + (\ w +) \ s +/I ';
$ Html = preg_replace_callback ($ strB, function ($ m) use ($ Array1) {return $ Array1 [0] [$ m [1] ;}, $ strA );
Echo $ Html;

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.